Python Dictionaries — in and out. Dictionaries are one of the most widely…
By: Chamanth Mvs
Tags: Programming, Python Programming, Data Science, Data Structures, Python

Iteration in Dictionaries

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

Iterating through dictionaries are quiet different from another 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 dictionary , we need to use .values() method. In the Fig-8, difference between iterating over lists and dictionaries can be seen(in terms of Values).

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

To iterate through both (key-value) pairs at a time in dictionary, we use .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 about dict comprehension in very brief manner because it is one of the advanced topic 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 .items() method. Conditional logics can also be written with in dict-comprehension (see Fig-11)

Methods in Dictionaries

In this part, I would briefly discuss about 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 object from memory. If you want to delete 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 single element from dictionaries.

2.copy()

Fig-13: copy method in dictionaries

copy() method will create a duplicate dictionary in different address of the memory. This can be tested as shown in the Fig-13. In this, “==” refers to whether both the values in two dictionaries are same or not. Whereas, “is” refers to whether both dictionaries (original as well as copied) refers to same address in the memory or not. Change in one of the both, will not impact 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— Key should be an iterable collection to the dictionary. All the iterables in key will be assigned to same value specified in the Value part, as shown in the Fig-14. This is rarely used method for creating dictionaries.

4.get()

Fig-15: get method in dictionary

get() method retrieves a key in an object and return None instead of keyError, if the key doesn’t exist.The biggest advantage is that, it doesn’t throw an error, even though if we try to access a key, which is not present in 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 pop() method to remove an element from a list. In dictionaries, we use it to remove a (key,value) pair. pop() method should be provided with at least one single argument corresponding to the key. It removes that particular (key-value) pair from dictionary by returning the value corresponding to the key that was removed. If we try to remove a key which is not in dictionary, then it will generate key-error, which can be overcomed by providing 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 (key-value) pair from 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 overwrites 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 existing one.

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