Python Tutorials: Learn Python Dictionary Data Structures in Detail

Python Tutorials: Learn Python Dictionary Data Structure in Detail with Real Examples
Written by Paayi Tech |19-Oct-2020 | 0 Comments | 649 Views

In this article, we will learn about the dictionary data structure in python. Dictionary is also known as hash maps. Hash maps data structure is the type in which values are stored corresponding to a key, and each value is extracted from the value of its key. Python dictionary is similar to the JSON data structures.

JSON is a JavaScript object notation in which data stores within the curly braces and each value has its key. Its key fetches the values. The function of searching is optimized when the key is known to the dictionary will be the most favorable in such a condition.

 

This is all the introduction of the dictionary. Now we will know about the details of the dictionary.

How to initialize the dictionary:

dic = {}

dic["name"] = "Pikachu"

dic["type"] = "electric"

dic["specie"] = "Pokemon"

print(dic)

 

This is the first method to initialize the dictionary. We first make empty curly braces, and then with each key, we assign its value. In the above example, we have created three keys name, type, and species. Each key is then assigned a value, and when we print the dictionary following output is given:

{'name': 'Pikachu', 'type': 'electric', 'species': 'Pokemon'}

 

As we can see, each key-value pair can be seen separated by the colon.

The second way to initialize the key is by using the dict () function. Following is the code to implement such a method:

dic = dict ()

dic["name"] = "Pikachu"

dic["type"] = "electric"

dic["specie"] = "Pokemon"

print(dic)

 

The dict function does the same as the empty curly braces.

The third way to initialize the dictionary is by converting the list to the dictionary. It is done in the following way:

ls = [("name”, "Pikachu"), ("type”, "Electric"), ("specie”, "Pokemon")]

 

print(dict(ls))

 

The above code will also act the same as mentioned above. The output will be the same, but in this case, a list contains tuple. The first value of the tuple will be converted to key and the second to value.

 

Accessing the values:

In dictionaries, values can be accessed by multiple methods. We will now see how to access the value of a dictionary in python.

 

By Key:

Value can be accessed by the key. With the key attribute, we have to give the key name in square brackets or a get function. Following is the way to access the value:

Code

ls = [("name”, "Pikachu"), ("type”, "Electric"), ("specie”, "Pokemon")]

data = dict(ls)

 

print (data["name"])

print (data["type"])

print (data["specie"])

 

print (data.get("name"))

print (data.get("type"))

print (data.get("specie"))

With the important method, we can access the value by these two methods.

 

Iteration on Dictionaries:

We can also iterate for loop over the dictionary. When for loop is iterated over a dictionary, it returns a key value, and by placing the key within square brackets, the value is extracted. Following is the method to get keys:

ls = [("name”, "Pikachu"), ("type”, "Electric"), ("specie”, "Pokemon")]

data = dict(ls)

for e in data:

    print(e)

The above code will output the key as follows:

Output

name

type

specie

 

Now, if we change the code a little bit and give these keys to the data variable, we will get the values:

ls = [("name”, "Pikachu"), ("type”, "Electric"), ("specie”, "Pokemon")]

data = dict(ls)

for e in data:

    print(e)

 

The output of the above code is shown below:

Output

 

Pikachu

Electric

Pokemon

 

Dictionary Comprehension:

Dictionary comprehension is a way to make a dictionary elegantly. We don’t use the conventional way of creating a dictionary by looping and assigning value to it. Instead, we make a dictionary is just one line as we have seen in a list comprehension

print ({x:x*x for x in range (9)})

 

 

In the above example, for each number as a key, there is a corresponding value, which is the square of the key. The output of the above statement is as follows:

{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64}

 

A list within dictionaries:

We cannot just only give the value to the key in dictionaries. We can also give the list within the dictionary.

Following is the way to give the list in the dictionary:

dic = {"ls1”: [1,2,3,4],"ls2”: [5,6,7,8]}

print(dic)

Similarly, we can give tuple, sets, and multidimensional lists in a dictionary

Nested Dictionary:

A nested dictionary is a dictionary that contains dictionaries within a dictionary. Just like a JSON object, we can create a nested dictionary. This allows us to hold more complex data.

For example, if somebody sends multiple messages, then we will save the data about the user in one key and multiple messages in multiple dictionaries. This will make it easier to manage the data. Nested dictionaries also allow holding data of different objects within the same dictionary.

For example, we have 10 students in a class, and each student has a unique roll number. So, by assigning the roll number as a key, we can store all the data of that particular student in a dictionary. Following is the code of the above example:

student = {1: {"name":"Ahmed","class":10},

           2: {"name":"Ali","class":9},

           3: {"name":"Amaar","class":4}

           }

print(student)

Here the 1, 2, and 3 are the registration number, and corresponding to each registration number is the information of that student. Now by unique id student, data can be fetched easily, and there will be no conflicts within it.

Built-in Functions:

Sorted:

Sorted return the list of key values. Following is the example of sorted with dictionaries:

dic = {"z":7,"g":4,"a":2}

print(sorted(dic))

Output

['a', 'g', 'z']

 

Len ():

len function returns the length of the dictionary:

How to get the values of all the keys:

We can get the value of keys by the dictionary using the following code:

dic = {"z":7,"g":4,"a":2}

a = dic.keys()

print(a)

 

Output

dict_keys (['z', 'g', 'a'])

 

Sort the dictionary by key:

Sorting is one of the main issues in the dictionary. The sorted function only returns the sorted value. To do the proper sorting of the dictionary, the following method is used to sort the dictionary:

dic = {"z":7,"g":4,"a":2}

 

key = dic.keys()

key = sorted(key)

for k in key:

    print (k, dic[k])

Output

a 2

g 4

z 7

 

Sort Dictionary by value:

Another major problem is to sort by the value. Sort by value is little complicated than sort by the key:

dic = {"z":7,"g":4,"a":2,"f":5,"e":9}

 

sort_dic = sorted(dic.items(), key= lambda kv:kv[1])

print(dict(sort_dic))

Output

 

{'a': 2, 'g': 4, 'f': 5, 'z': 7, 'e': 9}

 As it will return the sorted list with tuples in it so we then again have to convert it into the dictionary.





Login/Sign Up

Comments




Related Posts



© Copyright 2020, All Rights Reserved. paayi.com

This site uses cookies. By continuing to use this site or clicking "I Agree", you agree to the use of cookies. Read our cookies policy and privacy statement for more information.