Python DICTionary HowTo (Page: 1)
Dictionary in Python is an unsorted collection of key / value pairs. Dictionary in Python ideologically are very similar to hash in Perl
How to use dictionary element
The simplest way is to use value for given key in the dictionary is to call this key in square brakes. But if this key is not existing – then Fatal error will be called:
dic = {'a':0, 'b':1, 'c':2}
print(dic["c"]) # 2
print(dic["d"]) # KeyError: 'd'
To avoid this error, you can use method get(), which will give None if the key is absent
dic = {'a':0, 'b':1, 'c':2}
print(dic.get("b")) # 1
print(dic.get("d")) # None - no fatal error
Default value for absent element
Pretty common task for dictionary – make a counter for objects. For this make a key for every object and increase value accordingly. But the default value for absent key will make this taks a bit easier. Let's consider very simple task – make word popularity in the list.
counter = {}
words = ['aaa', 'bbb', 'aaa', 'ccc', 'bbb', 'ccc']
for word in words:
counter[word] = counter.get(word, 0) + 1
# {'aaa': 2, 'bbb': 2, 'ccc': 2}
dictionary with key “word” equal value of “word” + 1 for every new word. But is this key is not existing method .get() return default value “0” and Error is not risen.
How to add and remove element to dictionary in Python
How to Check if a given key already exists in a dictionary
Perform any action with the dictionary with non-existent key will finish with an error. Therefore it is a good idea to check of presence of the key
k = 'aad'
d = {'aaa': 14, 'aab': 13, 'aac': 12}
if k in d.keys():
print(k, "is present")
else:
print(k, "is absent") # aad is absent
How to remove element in dictionary by key
Removing element in dictionary is very simple. You need to know the key of element you would like to delete and use function del()
d = {'aaa': 14, 'aab': 13, 'aac': 12}
print(d) # {'aaa': 14, 'aab': 13, 'aac': 12}
del(d['aab'])
print(d) # {'aaa': 14, 'aac': 12}
It is better to check the presence of the key before removal, to make sure that the program will not crash in case of absent key
k = 'aac'
d = {'aaa': 14, 'aab': 13, 'aac': 12}
if k in d.keys():
del(d[k])
print(d) # {'aaa': 14, 'aab': 13}
How to remove element in dictionary by value
To remove all elements with dictionary with given value, it is easier to use comprehension. In fact we take all pairs from our dictionary and return them back if they values are not equal value prepared for removal
to_remove = 13
d = {'aaa': 14, 'aab': 13, 'aac': 12}
d = {key:val for key, val in d.items() if val != to_remove}
print(d) # {'aaa': 14, 'aac': 12}
How to compare two dictionaries
It is very easy to compare two dictionaries in Python. Use standard operation == for comparison. Please note, that this comparison is also check case for every string component and also it compare type for every element in dictionary
d1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
d2 = {'d': 4, 'a': 1, 'b': 2, 'c': 3}
d3 = {'a': 1, 'b': 2.0, 'C': 3, 'd': 4}
print(d1 == d2) # True
print(d1 == d3) # False
How to iterate over dictionary
How to loop over key in dictionary
Very simple and common way of iterations over dictionary is to loop oner key only. In most cases this way of iterations is used
d = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
for k in d:
d[k] += 1
print(d) # {'a': 2, 'b': 3, 'c': 4, 'd': 5}
How to loop over key / value in dictionary
For more complicated cases it is more convenient to have pair key / value in every iterations
d = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
for k, v in d.items():
print(v, end=', ') # 1, 2, 3, 4,
But it is necessary to remember, that value is a shallow copy of the dictionary value, therefore:
d1 = {'a': 1, 'b': 2}
for k, v in d1.items():
v = v ** 2 # NOT affecting original dictionary
print(d1) # {'a': 1, 'b': 2}
d2 = {'a': [1, 2], 'b': [3, 4]}
for k, v in d2.items():
v.append(k) # DO affect original dictionary
print(d2) # {'a': [1, 2, 'a'], 'b': [3, 4, 'b']}
Published: 2021-10-13 14:31:51
Updated: 2021-10-20 14:27:27