November 13, 2021

Python Dictionaries

Dictionaries in Python


Dictionaries are mutable.

These are like Composite Arrays in Shell Scripting.
Dictionary is key, value pair.
Keys are unique in dictionaries and hence cannot have duplicate keys whereas values can be repeated across any key.
Only Immutable data types/structures can be keys - can be int, float, bool, string, tuple. Key should NOT be a list or dictionary.
Dictionaries are unordered elements.

comp_arr={'Name':'Satya', 'Gender':'Male'}
symbol = {"H": "hydrogen", "He": "helium", "C": "carbon", "O": "oxygen", "N": "nitrogen"}
>>> dict = {1 : 'hello', 'two' : 42, 'blah' : [1,2,3]}
nobel_prize_winners = { (1979, "physics"): ["Glashow", "Salam", "Weinberg"],   (1962, "chemistry"): ["Hodgkin"],   (1984, "biology"): ["McClintock"] }
new_dict=dict(country='India',Songs=['sfsak','dfksdfks 8wer'])
urls = {} # creates an empty dictionary

dict["key"] = {}
var['val'] = 40.2054
data['Age'] = 34
data["new key"] = "value"

comp_arr['Name']
>>> symbol["C"]
comp_arr.get('Name')
comp_arr.get('Surname','default')
print d.get('fish', 'N/A')

comp_arr.keys() # will not return in same order
print(list(comp_arr.keys()))

comp_arr.values()
print(list(comp_arr.values()))

sorted(d.keys())

print(sorted(pyDict, reverse=True))
list(d.keys())

comp_arr.items()
for i in dict: print(i) # By default, the iteration is over the keys
for animal, legs in d.iteritems(): print 'A %s has %d legs' % (animal, legs)
comp_arr.has_key('Qualification')
print('key' in dict)
print(xl['1700'].head())
print(len(dict))
similarities[similarity].append(n)

>>> symbol.update( {"P": "phosphorous", "S": "sulfur"} )

>>> del symbol['C']

del dict['two']

>>> del(d[22])

>>> d2 = d.copy()

type(symbol)


similarities = defaultdict(list)


Related 
Python Articles:  Lists in Python       Tuples in Python


No comments:

Post a Comment