Python Dictionary Built-in Functions: All You Need to Know
Essential methods to work with my favorite data structure.
Dictionaries are my favorite data structure. It is called HashMaps in Java and Maps in C++.
A brief intro about the dictionaries— It is a data structure that maps your key-value pairs. You can store another data structure corresponding to a “key”.
The speed of the lookup and the way dictionaries stores data are elegant. I can use dictionaries in place of any other data structure (I know it is not efficient, I’m just saying).
I’ve been using dictionaries for some time now but I didn’t know about a few methods until recently that give much more power to leverage the great power of dictionaries.
Before we dive into the lesser-known methods. Let’s look at some of the most commonly used methods. You can skip past any method which you feel you already know.
get()
get()
method is used to fetch the value of a specified key.
emojiDict = {'smile': '🙂', 'sad': '🙁', 'laugh': '😂'}
print(emojiDict.get('smile'))
## 🙂
If you are getting a key error while using the get()
method, it is due to the fact that the key is not present in the dictionary. You can pass an additional parameter with the get()
method to specify a default value.
emojiDict = {'smile': '🙂', 'sad': '🙁', 'laugh': '😂'}
print(emojiDict.get('cry', 'Not present'))
## Not present
copy()
copy()
creates a shallow copy of the dictionary.
clear()
clear()
as the name suggests, erases all the data stored inside the dictionary.
items()
items()
returns a list of tuples of the key-value pairs stored inside the dictionary.
emojiDict = {'smile': '🙂', 'sad': '🙁', 'laugh': '😂'}
print(emojiDict.items())
## dict_items([('smile', '🙂'), ('sad', '🙁'), ('laugh', '😂')])
keys()
keys()
returns a list of keys present in the dictionary.
emojiDict = {'smile': '🙂', 'sad': '🙁', 'laugh': '😂'}
print(emojiDict.keys())
## dict_keys(['smile', 'sad', 'laugh'])
values()
values()
return a list of values present in the dictionary.
emojiDict = {'smile': '🙂', 'sad': '🙁', 'laugh': '😂'}
print(emojiDict.values())
## dict_values(['🙂', '🙁', '😂'])
Now that we are acquainted with the commonly used methods, we can learn about the new methods.
fromkeys()
fromkeys()
method lets you create a dictionary with your keys having the same value. It is quite useful when we have the keys and we want to initialize the dictionary.
countKeys = ['countA', 'countB', 'countC']
countValue = 0
countDict = dict.fromkeys(countKeys, countValue)
print(countDict)
## {'countA': 0, 'countB': 0, 'countC': 0}
countDict = dict.fromkeys(countKeys, countValue)
print(countDict)
zip()
zip()
lets you create a dictionary where we have 2 lists where one list contains the keys and the other list contains the values.
emojiKeys = ['smile', 'sad', 'laugh']
emojiValues = ['🙂', '🙁', '😂']
emojiDict = dict(zip(emojiKeys, emojiValues))
print(emojiDict)
## {'smile': '🙂', 'sad': '🙁', 'laugh': '😂'}
pop()
pop()
method lets you erase the key-value pair from the dictionary by the key. It returns the removed value.
emojiDict = {'smile': '🙂', 'sad': '🙁', 'laugh': '😂'}
noSadDict = emojiDict.pop('sad')
print(noSadDict) ## 🙁
print(emojiDict) ## {'smile': '🙂', 'laugh': '😂'}
popitems()
It removes the last inserted key-value pair from the dictionary. It returns the tuple of the removed item.
emojiDict = {'smile': '🙂', 'sad': '🙁', 'laugh': '😂'}
noLaughDict = emojiDict.popitem()
print(noLaughDict) ## ('laugh', '😂')
print(emojiDict) ## {'smile': '🙂', 'sad': '🙁'}
setdefault()
Returns the value of an item with the given key. If the key is not found, the key-value pair is inserted into the dictionary. I have started using this to count the frequency of elements.
countDict = {}
countDict.setdefault('1', 1)
countDict.setdefault('1', 5)
print(countDict) ## {'1': 1}
Note here that the value is not changed.
update()
update()
is used to modify the value corresponding to the specified key.
countDict = {}
countDict.setdefault('1', 1)
countDict.update({'1':5})
print(countDict) ## {'1': 5}
Note here that we have to pass the new dictionary as the argument to update the dictionary.
These are almost all the methods that are essential and handy to use with dictionaries. You can do almost anything with dictionaries with these methods.
Don’t waste your time with old learning techniques anymore. Grab my free 7-Step Learning Framework to accelerate your learning and make the skills stick.
If you liked the article, there are a lot more like this on Medium. You can sign up to read them for just $5 a month.
Here is the link for unlimited access to every content here on Medium. If you sign up by using this link, I’ll earn a small amount at no additional cost to you.