Working with Python dictionaries: a cheat sheet | by Mahbubul Alam | Towards Data Science

Dictionaries in Python are a collection of key-value pairs — meaning every item in the dictionary has a key and an associated value.
If we want to write down prices of some items in a grocery store, normally we will note them on a piece of paper like this:
eggs - 4.99banana - 1.49cheese- 4.5eggplant - 2.5bread - 3.99
In Python dictionary lingo, the name of each item is “key” and the associated price is “value” and they appear in pairs. We can represent the same in a Python dictionary data structure as follows:
{"eggs": 4.99,"banana": 1.49,"cheese": 4.5,"eggplant": 2.5,"bread": 3.99}
Notice the differences. In the dictionary
each key is within quotation marks because they are strings
the associated values are not quoted because they are numeric
keys and values are separated by a colon (:)
the items are comma-separated
Now, in the first items we have {"eggs”: 4.99} but in reality, eggs can have several values — one for brown eggs, one for white eggs and one for organic eggs — and python dictionaries allows for adding more than one value in the dictionary such that {“eggs”: [3.99, 4.99, 5.50]}.
Let’s give this dictionary a name and play with it:
grocery_items = {"eggs": [3.99, 4.99, 5.50],"banana": 1.49,"cheese": 4.5,"eggplant": 2.5,"bread": 3.99}
You can open your IDE/text editor and follow along with the codes below to work with this dictionary we just created.
We’ve built our initial dictionary with 5 items but we can grow it by adding more items:
grocery_items["onion"] = 3.50Out: {"eggs": [3.99, 4.99, 5.50], "banana": 1.49, "cheese": 4.5, "eggplant": 2.5, "bread": 3.99, "onion": 3.50}
You can add multiple items in a similar fashion.
We can also do the opposite — remove one or more items from this list. There are a couple of ways to do that:
Remove the last item using popitem() method:
grocery_items.popitem()Out: {"eggs": [3.99, 4.99, 5.50], "banana": 1.49, "cheese": 4.5, "eggplant": 2.5, "bread": 3.99}
Or remove an item by its key name using just pop() method:
grocery_items.pop("banana")Out: {"eggs": [3.99, 4.99, 5.50], "cheese": 4.5, "eggplant": 2.5, "bread": 3.99}
And finally, you can clear the whole dictionary (i.e. making it empty) with clear() method and delete the entire dictionary with del keyword (just be careful if you ever have to use it).
You may be wondering where someone can find all those methods? Just hit the “tab” key on the keyboard and all methods will pop up.
It’s often necessary to get a list of keys or values in the dictionary for further analysis (we’ll see later why).
To access all the keys:
grocery_items.keys()Out: dict_keys(['eggs', 'banana', 'cheese', 'eggplant', 'bread'])
To access all values instead:
grocery_items.values()Out: dict_values([[3.99, 4.99, 5.5], 1.49, 4.5, 2.5, 3.99])
We can also query the dictionary to access the value of a specific key (e.g. the price of bananas). There are a couple of ways to do that:
# access values by keygrocery_items["banana"]# or grocery_items.get("banana")Out: 1.49
But what about eggs? We have three different prices for eggs. We can choose to access all prices:
grocery_items.get("eggs")Out: [3.99, 4.99, 5.5]
We can also choose to access just the first one from the list by index position:
grocery_items.get("eggs")[0]Out: 3.99
In fact, we can access more complex nested dictionary items/keys/values in a similar fashion.
Besides the methods the above, which are most frequently used with a dictionary, there are a few methods and functions which can come in handy in data analysis:
To get the number of items in the dictionary:
len(grocery_items)Out: 5
To change the value of a key:
grocery_items.update({"banana": 0.85})
To cast the keys as a list:
list(grocery_items)Out: ['eggs', 'banana', 'cheese', 'eggplant', 'bread']
If the dictionary is really large, we can check whether a key exists:
"potato" in grocery_itemsOut: False
And finally, for returning the string representation of a dictionary:
str(grocery_items)Out: "{'apple': 2.5, 'orange': 4.99, 'banana': 0.59}"
It is often necessary to change dictionary elements or extract specific values or keys based on certain conditions. Since dictionaries are iterable objects, for loops are often used for such operations. Here are a couple of examples:
A simple loop to print all the keys:
for i in grocery_items:    print(i)Out:eggsbananacheeseeggplantbread
Or a for loop for conditional filtering of dictionary keys:
for i in grocery_items.keys():    if i.startswith("e"):        print(i)Out:eggseggplant
Like list comprehensions, Python also supports dictionary comprehensions to perform different kinds of operations. The for loops we created above could also be expressed in dictionary comprehension syntax.
For example, to print the values of a dictionary:
[x for x in grocery_items.values()]Out:[[3.99, 4.99, 5.5], 1.49, 4.5, 2.5, 3.99]
To summarise, we have covered in this article:
Python dictionaries are iterable objects with key-value pairs
dictionaries can be edited to add, remove and update values
dictionary elements can be accessed with methods such as .keys(), .values() and .items()
dictionaries are iterable objects, so Python allows for loops or dictionary comprehensions.
I left many other methods and functionalities out, but I hope this gives a head start to build a cheat sheet to work with Python dictionary objects.
If you have comments feel free to write them down below or connect with me via Medium, Twitter or LinkedIn.