Python Dictionaries — in and out

Chamanth mvs
8 min readOct 22, 2019

Dictionaries are one of the most widely used and important data structures in python. Unlike data structures in python( lists, tuples, strings, sets, and frozen sets), where they have only value as an element, the dictionary has a key-value pair.

I assume that you have a basic idea about lists and tuples in python because, in this blog, I would discuss only dictionaries and compare lists with dictionaries in a few instances. The following are the topics that will be discussed.

  1. Few limitations of lists(not in terms of technical), where a dictionary can be used.
  2. How dictionaries are created and how can we access them?
  3. Power of dictionary (in oversimplified view).
  4. Iterate over dictionaries using loops and dictionary comprehensions.

Limitations of Lists (not in terms of technical)

Lists are mostly used as simple data structures in python but in general, they are used to store particular sources of data like “list of names”, “list of cities” … any homogenous types.

Fig-1 : creating a list of elements of different datatype

Let’s assume we need to store information about the university (name, year of establishment, location, type of organization, number of students). We can represent it by using the list as shown in the picture on the left.

But in the above picture, we are not able to decode about few elements in the list like 11,574, which indicates the “number of students”, it is known only to the person who created it. So, it is evident that the above list is not informative and clear. Dictionaries can be used in such scenarios, which describes in detail. Let’s see how to create them.

Creation and Access dictionaries

Dictionaries can store all kinds of data like lists (they can even store lists, tuples, or another dictionary as elements[values]). The dictionary is always represented by {} in python.

Creation

There are various methods for creating a dictionary. Values can be of any data type (ranging from int to nested dictionaries). Unlike lists, where lists have indices as integers (0,1,2…) but in dictionaries, Keys are considered as indices and they can be of mixed types like (int, float, boolean, or string).

Fig-2 : various methods of creating dictionary

There are various methods for creating a dictionary. I will discuss the three mostly used methods

Method-1: a dictionary can be created using the dict() function, which is an inbuilt function in python.

Method-2: by using key-value pairs. Key-Value pairs are always separated by “:”(colon) in the dictionary. This is the most used method among all, and forgetting to separate key and value by “:” will result in an error.

Method-3: They can also be created by using a list of tuples as shown in the image.

Any of the three will generate the same dictionary. It is evident from Fig-2 that, the same data which is presented with help of a dictionary is more meaningful than the lists in Fig-1.

Accessing dictionaries

Fig-3: Accessing dictionary

Unlike Lists, Dictionaries are an unordered collections of items. So, we can’t index them (like we do in the list, for example-List[0]=> to access the first element in the list). Dictionaries can only be accessed using keys.

Most common errors which might encounter while accessing the dictionary

Fig-4:Key error and name error within dictionaries
  1. If we don’t have a key and we try to access the dictionary with help of an unavailable key, then python throws a “Key error” saying that you have no such key in the dictionary as shown in the image
  2. We will encounter a “Name error” in the dictionary, if we use a variable in place of the key, before assigning some arbitrary value to a variable.

An oversimplified view of internal storage of dictionary

Fig-5:A very simplified view of how dict is internally stored

It is how internal dict is stored in. But, when we visualize dict (it represents in {}). There are two columns(keys and values) corresponding to each. This pattern follows any number of pairs in the dictionary.

Power of a Dictionary

Fig-6: How search is different from lists/tuples to dictionary

Let’s assume we need to find out city named “Dublin” in the given list. Usually, search in lists happens Sequentially. It starts at the 0(th) index and searches till n-1(th) in a list of “n” elements. (The same is shown in the figure, to find “Dublin”, it starts from the 0(th) index and moves forward. the same is the case with tuples too.

But, when it comes to a dictionary or hash tables, Hashing has been used for dictionary lookup and they(dictionary or hash tables) are designed in a way that, they can directly reach to the exact place where “Dublin” is stored (not a sequential search). So, Dictionaries are a much faster and more efficient way of searching or processing information when compared to lists or tuples. In technical terms, we can say that its (dictionaries) time complexity is very low.

Iteration in Dictionaries

Fig-7: Iterating through dictionaries (img source:real Python)

Iterating through dictionaries is quite different from other data structures because, in dictionaries we have (key-value) pairs whereas, in lists or tuples we only have one single element at each index, and also list on its own is iterable.

Fig-8: Iterating through values in dictionary
Fig-9:various methods in iterating over keys in dictionary
Fig-10: iterating through both keys and values

In order to extract values from the dictionary, we need to use the .values() method. In Fig-8, the difference between iterating over lists and dictionaries can be seen(in terms of Values).

Similarly, we need to use the .keys() method to iterate over keys in the dictionary. As you can see in Fig-9, the same can be done without using the “.keys()” method also (it is anyways not recommended).

To iterate through both (key-value) pairs at a time in the dictionary, we use the .items() method. This method returns an iterable collection (list of tuples.

Dict comprehension

These are similar to list comprehension (prior understanding of list comprehension will help in understanding better). I would cover dict comprehension in a very brief manner because it is one of the advanced topics in dictionaries.

Fig-11: Dict Comprehension

Syntax: {__:__for__in__} - it iterates over keys by default. If we want to iterate over keys and values, we should use the .items() method. Conditional logic can also be written within dict-comprehension (see Fig-11)

Methods in Dictionaries

In this part, I would briefly discuss a few inbuilt methods (clear, copy, fromkeys, get, pop, popitem)of dictionary data structure.

1.clear()

Fig-12 : clear and del in dictionary

clear() — — clears all the ‘‘keys and values’’ in a dictionary . But it doesn’t delete entire dictionary objects from memory. If you want to delete the entire dictionary object from memory, then we need to use del. If you further try to access deleted dictionary then you will get “NameError”, del can also be used to remove a single element from dictionaries.

2.copy()

Fig-13: copy method in dictionaries

copy() method will create a duplicate dictionary in a different address of the memory. This can be tested as shown in Fig-13. In this, “==” refers to whether both the values in two dictionaries are the same or not. Whereas, “is” refers to whether both dictionaries (original as well as copied) refer to the same address in the memory or not. Change in one of the both, will not impact the other as both are stored at different addresses.

3.fromkeys()

Fig-14 : fromkeys() method in dictionary

fromkeys() creates key-value pairs from comma-separated values. condition to be followed— The key should be an iterable collection of the dictionary. All the iterables in the key will be assigned to the same value specified in the Value part, as shown in Fig-14. This is a rarely used method for creating dictionaries.

4.get()

Fig-15: get method in dictionary

get() method retrieves a key in an object and returns None instead of keyError if the key doesn’t exist. The biggest advantage is that it doesn’t throw an error, even if we try to access a key, which is not present in the dictionary.

In Fig-15 —- sample_dict.get(‘a’) is equivalent to sample_dict[‘a’]

5.pop()

Fig-16:pop() method in dictionary

In lists, we use the pop() method to remove an element from a list. In dictionaries, we use it to remove a (key, value) pair, the pop() method should be provided with at least one single argument corresponding to the key. It removes that particular (key-value) pair from the dictionary by returning the value corresponding to the key that was removed. If we try to remove a key that is not in the dictionary, then it will generate a key error, which can be overcome by providing an optional argument to it(as shown in last in Fig-16).

6.popitem()

Fig-17: popitem() method in dictionary

If we want to randomly remove the (key-value) pair from the dictionary, then we should use popitem() method. If any argument is provided to popitem(), then we will get an error because it doesn’t take any argument.

7.update()

Fig-18: update() method in dictionary

update() will change (key,value) in a dictionary with another set of key-value pairs. It will also overwrite an existing key. It will overwrite and edit the properties however, it won’t remove them if we pass an empty dictionary to update with the existing one.

To list all available methods and attributes of a dictionary, use dir(dictionary_oject)

Fig-19: dir(dict_object)

Conclusion

Most of the basics regarding python dictionaries have been discussed in this blog.

The two most frequently used Python types are Lists and dictionaries. There are several similarities between each other, but they differ in how their elements are accessed and a few methods vary from one over the other.

--

--

Chamanth mvs

Data Science and ML practitioner | I share my learnings and thoughts here