Python's Dictionary in Details

Python's Dictionary in Details

Dictionary is a composite datatype in the Python programming language. In a way, it is similar to lists. Lists are a collection of elements. Dictionaries are a collection of key, value pairs. Solutions to many programming problems can be easy and more concise with dictionaries. Here I am going to explain all the important methods in the dictionary and some problem-solving with examples.

Let’s define a simple dictionary.

d = {'a': 1, 'b':5, 'c': 3, 'd': 2, 'e': 8, 'f': 6}
  1. Add a new element in this dictionary:
d['s'] = 12
print(d)

Dictionary d looks like this now:

{'a': 1, 'b': 5, 'c': 3, 'd': 2, 'f': 6, 's': 12}

2. delete the element e from the dictionary d.

del d['e']

3. Get the value of the key a.

d['a']
#Output: 1

4. The value of ‘a’ looks too small. Update the value of element a to 10.

d['a'] = 10

5. Add 3 to the value of the element s.

d['s'] += d['s'] + 3

6. Check the length of the dictionary d. If it is less than 9, then add three more elements to it.

if len(d) < 8:
    d.update({'t': 21, 'h': 9, 'p':14})
print(d)
'''
Output:
{'a': 10, 'b': 5, 'c': 3, 'd': 2, 'f': 6, 's': 12, 't': 21, 'h': 9, 'p': 14}
'''

7. Make a list of all the keys.




d.keys()##Output looks like this:dict_keys([‘a’, ‘b’, ‘c’, ‘d’, ‘f’, ‘s’, ‘t’, ‘h’, ‘p’])

8. Make a list of all the values.

d.values()
##Output looks like this:
dict_values([10, 5, 3, 2, 6, 27, 21, 9, 14])

9. Find out which alphabet has the biggest value.

max = 0
max_key = 'a'
for k, v in d.items():
    if v > max:
        max_key = k
        max = d[max_key]
print(max_key)

The answer came out to be ‘t’.

10. Sort the keys of the dictionary d by the values in ascending order.

sorted(d, key=lambda x: d[x])
#Output:
['d', 'c', 'b', 'f', 'h', 'p', 't', 's']

11. Find out how many times each word appeared in the following sentences.

sentences = "I love my country. My country is the best in the world. We have the best athletes in the world."

Let’s make a dictionary where the keys will be the words in these sentences and the values will be the frequency that the words appeared.

These are steps to solve this problem:

a. Initialize an empty dictionary ‘sen_map’

b. Make the sentences all lower case

c. Iterate over each word in the sentences

d. Check if a word exists in the sen_map

e. If not then add the word with a value of 1

f. Otherwise, update the value of that word by 1

sen_map = {}  
sentences = sentences.lower() 
for i in sentences.split(): 
    if i not in sen_map:   
        sen_map[i] = 1  
    sen_map[i] += 1  
sen_map'''Output
{'i': 2,  'love': 2,  'my': 3,  'country.': 2,  'country': 2,  'is': 2,  'the': 5,  'best': 3,  'in': 3,  'world.': 3,  'we': 2,  'have': 2,  'athletes': 2}'''

Dictionaries can be nested like lists. Here is an example:




Gold_medals = {'USA': {'Wrestling': 3, 'Long Jump': 3, 'Basketball': 5},
              'China': {'Wrestling': 1, 'Long Jump': 5, 'Basketball': 3},
              'England': {'Wrestling': 2, 'Long Jump': 7, 'Basketball': 0}}

12. How many gold medals did the USA win in the long jump?

Gold_medals['USA']['Long Jump']

The output is 3 as we can see in the dictionary above.

Another way of organizing information in dictionaries is on a list.

Here is an example:

students = [{'Name': 'John Smith', 'Age': 12, 'Score': 90},
           {'Name': 'Laila Jones', 'Age': 11, 'Score': 82},
           {'Name': 'Omar Martinez', 'Age': 10, 'Score': 70},
           {'Name': 'Romana Raha', 'Age': 13, 'Score': 78},]

13. Return the name of the student who scored the highest in the class.

Let’s solve this step by step. First sort ‘students’ in descending order.

sorted(students, key=lambda x: x['Score'], reverse=True)
#Output:
'''[{'Name': 'John Smith', 'Age': 12, 'Score': 90},  {'Name': 'Laila Jones', 'Age': 11, 'Score': 82},  {'Name': 'Romana Raha', 'Age': 13, 'Score': 78},  {'Name': 'Omar Martinez', 'Age': 10, 'Score': 70}]'''

Capture the first dictionary of the list ‘students’.

sorted(students, key=lambda x: x['Score'], reverse=True)[0]'''Output
{'Name': 'John Smith', 'Age': 12, 'Score': 90}'''

Finally, get the name of the student.

sorted(students, key=lambda x: x['Score'], reverse=True)[0]['Name']

This one line of code will return the name of the student. That is, ‘John Smith’.

I tried to explain the methods of dictionaries first and then presented some examples to show how to work with dictionaries. I hope this was helpful.

Here is the video tutorial on Dictionary:

#programming #Python #PythonProgramming

Leave a Reply

Close Menu