This is the forth in a series of posts on common pythonic idioms, so if you haven’t seen the previous two, you should definitely go and give them a read.
STEP ONE: MASTER DICTIONARIES, STEP TWO: TAKE OVER THE WORLD
OK, obviously you can’t take over the world with dictionaries, but mastering them will seriously up your programming game.
Dictionaries are a fairly large topic with many applications and ways to manipulate them. I won’t be covering everything about dictionaries in this post, but here are some pythonic idioms that I think are especially useful.
Looping over dictionary keys
One of the most basic things you can do with a dictionary is to loop over its keys. It’s also something that you will be doing very frequently, so let’s do it the Python way.
#How not to loop over dictionary keys for k in dic.keys(): print(k) #How to loop over dictionary keys for k in dic: print(k)
As shown above the preferred way to loop over keys in python is to actually not use the dictionary.keys() method. All that is needed is the reference to the dictionary.
Looping over key/value pairs
Another task you will often find yourself needing to do is looping over key/value pairs. As per usual with Python there are a couple of quick, easy and clean ways to do this.
#looping over keys for k in dic: print(k) print(dic[k]) #looping over key/value pairs for k, val in dic.items(): print(k) print(val)
These are two different ways of looping over key/value pairs in a dictionary. The first loops over the keys in the dictionary then using the keys retrieves the values. The second loops over the items in the dictionary, that is they key/value pairs and unpacks them into two variables.
Using dictionary.get() to get values
What if you want to get the value associated with a key in a dictionary, but you don’t actually know if that key exists or not. Python has you covered.
#How to use get() to get values val = dic.get('James', 'Could not be found')
If the key ‘James’ exists in the dictionary dic, this statement assigns the value that is paired with ‘James’ to the variable val. If the key ‘James’ doesn’t exist however, the default value, which is the second argument in the function call will be assigned. You can read more about get() in the Python documentation.
Deleting items that meet a certain criteria
I learnt this Python trick recently and absolutely love the power of it. Usually this kind of task would require a loop and conditionals. In Python, it’s just one line.
#Deleting keys that meet a certain criteria dic = {k : dic[k] for k in dic if not len(k) < 5}
The syntax here is fairly simple too if you break it down. {key : value for key in dictionary [condition]}. The above statement creates a new dictionary that contains all key/value pairs in dic where the key has a length of less than 5.
Combining two lists into a dictionary
Say you have a list of given names and a list of surnames, but you want a dictionary of surname/given name pairs, what do you do? You zip them.
#Combining lists into a dictionary f_names = ["Jamal", "Henry", "Phillip", "George"] l_names = ["Moir", "Williams", "Clarke", "Smith"] names = dict(zip(f_names, l_names))
This idiom here takes the lists f_names and l_names and combines to form a dictionary of last name/first name pairs. Quick, simple and like a lot of other Python idioms, one line. You can read more about zip() in the Python documentation.
There we have it, some pythonic idioms for dictionaries that I have found to be particularly useful, hopefully they will help you level up your python code too.
If you would like to know more about the dictionary data structure itself in Python, you can take a look at the documentation here.
‘Ello, I’m Jamal – a Tokyo-based, indie-hacking, FinTech software developer with a dependence on data.
I write Shakespeare-grade code, nowadays mostly in Python and JavaScript and productivity runs in my veins.
I’m friendly, so feel free to say hello!