Which method would you use to returns all the elements in the dictionary as a list of tuples?

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

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

  1. Few limitations of lists(not in terms of technical), where 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 and simple data structure in python but in general, they are used to store particular source of data like “lists 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 university (name,year of establishment,location,type of organization,number of students). We can represent it by using list as shown in picture on the left.

But in the above picture, we are not able decode about few elements in the list like 11,574, which indicates “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 Accessing dictionaries

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

Creation

There are various methods in 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, string).

Fig-2 : various methods of creating dictionary

There are various methods in creating dictionary. I will discuss three mostly used methods

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

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

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

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

Accessing dictionaries

Fig-3: Accessing dictionary

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

Most common errors which might encounter while accessing dictionary

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

Oversimplified view of internal storage of dictionary

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

It is how internally dict is stored in. But, when we visualize dict (it represents in {}). There are two columns(keys and values) corresponding to each. This patterns follows to any number of pairs in 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 0(th) index and searches till n-1(th) in a list of “n” elements. (The same is shown in figure, to find “Dublin”, it starts from 0(th) index and moves forward. the same is case with tuples too.

But, when it comes to 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 exact place where “Dublin” is stored (not a sequential search). So, Dictionaries are much faster and efficient way of searching or processing information when compared to lists or tuples. In technical terms, we can say that it’s(dictionaries) time complexity is very low.

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 dictionaryFig-9:various methods in iterating over keys in dictionaryFig-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 followedKey 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)

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 few several similarities between each other, but they differ in how their elements are accessed and few methods vary between one over the other.

Thank you for reading so far. I am committed to improving my style and presentation methods. So, if you have any suggestions or have something to share with, feel free to comment or contact me through linked-in here.

Which method would you use to returns all the elements in a dictionary as a list of key

In Python Dictionary, items() method is used to return the list with all dictionary keys with values. Parameters: This method takes no parameters. Returns: A view object that displays a list of a given dictionary's (key, value) tuple pair.

How do I turn my dictionary into a list of tuples?

Use zip() to convert all pairs of dictionary to list of tuples.
dict. keys(): Returns an iterable sequence of all keys of dictionary..
dict. values(): Returns an iterable sequence of all values of dictionary..

How do you convert the list of elements to set tuple and dictionary?

Using the append function we just added the values to the dictionary. This is a simple method of conversion from a list or tuple to a dictionary. Here we pass a tuple into the dict() method which converts the tuple into the corresponding dictionary.

How do you turn a dictionary into a list?

The first method is dict. items() to convert a dictionary into the list. This method is used to iterate the elements of the dictionary. Using list() we will get all the items converted into the list.