Python Programming Tutorial – Dictionary

Reading Time: 5 minutes

This is a continuation of the Python Programming Tutorial series for beginners. Previously, I’ve posted articles on Python Programming Introduction, Python Programming Data Types Introduction, Python Programming Built-in Methods, Python Programming Tutorials- Numbers, Python Programming Tutorial- Lists, and Python Programming Tutorial – Strings. You can find extra practice questions on this blog Python Programming Tutorial Practice Exercises.

This tutorial is also a Q&A themes article like my previous python string article.

1. What is python dictionary? How does it work?

Python Dictionary objects are data types that are enclosed in curly braces ‘{}’ and have key and value pairs and each pair is separate by a comma.

Dictionary is mapped. Meaning since it has key and value pair, a meaningful key can save a lot of trouble for coders, like using an address key to save all the addresses, an id key for all id’s and so on. Moreover, as of python >3.6, dictionaries also preserve the order.

# Creating a dictionary 
# var_name = {key:value} or var_name = dict({key:value})
user_info = {'name': 'Nibesh', 'education': 'Bachelors Degree', 'age': 27}

# Print type
print("Variable user_info is a {}.".format(type(user_info)))

# Print Dictionary
print(user_info)

# Now to get a specific information just fetch it using key.
print(user_info['name'])


Output

Variable user_info is a <class 'dict'>.
{'name': 'Nibesh', 'education': 'Bachelors Degree', 'age': 27}
Nibesh

1.1 How to I get keys of dictionary?

Dictionary comes with keys() method that provides all list of all the keys in dictionary.

print(user_info.keys())

Output

dict_keys(['name', 'education', 'age'])

1.2 How to I get values of dictionary?

Dictionary comes with values() method that provides all list of all the keys in dictionary.

print(user_info.values())

Output

dict_values(['Nibesh', 'Bachelors Degree', 27])

1.3 How to get key and value pair of a dictionary?

Dictionary comes with method items() method that returns list consisting of key and value tuples.

print(user_info.items())

Output

dict_items([('name', 'Nibesh'), ('education', 'Bachelors Degree'), ('age', 27)])

1.4 How do I check if key exists in a dictionary?

You can use if statement with in to check if the key exists.

if 'name' in user_info:
    print(user_info['name'])

Output

Nibesh

2. Are dictionary mutable?

Yes, the python dictionary is a mutable object. Meaning, we can change, add or remove key-value pairs after assigning.

# Mutable Dict
student_info = dict({'id': 12,
                     'nationality': 'China',
                     'data_enrolled': 2015,
                     'is_present': 'No',
                     'gender': 'Male'
                     })


print("Student info original: ", student_info)

# We made a mistake while gender registration
# Lets correct it
# Lets change the gender to female

student_info['gender'] = 'Female'
print("Student info after corrections: ", student_info)

Output

Student info original:  {'id': 12, 'nationality': 'China', 'data_enrolled': 2015, 'is_present': 'No', 'gender': 'Male'}

Student info after corrections:  {'id': 12, 'nationality': 'China', 'data_enrolled': 2015, 'is_present': 'No', 'gender': 'Female'}

3. Is it possible to find length of a dictionary?

Yes, len() can provide length for dictionary too.

student_info = dict({'id': 12,
                     'nationality': 'China',
                     'data_enrolled': 2015,
                     'is_present': 'No',
                     'gender': 'Male'
                     })

print(len(student_info))

Output

5

4. What’s the difference between list.pop() and dictionary.pop()

The pop() method in list the last item in the list, however, the pop() method in the dictionary can remove a specified item. The dict.popitem() would be the equivalent of list.pop(). FYI, if you want to clear the dictionary in one fell swoop use the clear() method.

recurrence_dict = {
    'current_location': 'Usa',
    'job': 'sofware engineer',
    'older_location': 'Canada'
}

print("Before popping: ", recurrence_dict)


# Lets remove the last item
recurrence_dict.popitem()

print("After popping: ", recurrence_dict)

Output

Before popping:  {'current_location': 'Usa', 'job': 'sofware engineer', 'older_location': 'Canada'}

After popping:  {'current_location': 'Usa', 'job': 'sofware engineer'}

5. How to access items in nested dictionary items?

Nested dictionary items is just another layer of dictionary, peel each layer of onion.

# Nested Dictionary  with dictionary
user_info = {1: {'name': 'Jason', 'age': '17', 'gender': 'Male'},
             2: {'name': 'Jessica', 'age': '30', 'gender': 'Female'}
             }


# Accessing Dictionary inside dictionary
# Lets get gender
print(user_info[1]['gender'])
# Nested Dictionary  with list
subject_info = {'Science Topics': ['Mathematics', 'Computer Science', 'Biology'],
                'Arts Topics': ['Music', 'Dance']
                }


# Accessing list inside dictionary
# Lest access last item in the list
print(subject_info['Science Topics'][-1])

Output

Male
Biology

6. How to sort dictionary keys and values?

Dictionary items can be sorted by both keys and values.

# Sort dictionary

# By keys
students_by_regions_finland = {
    'uusimaa': 1000000,
    'nothern ostrobothina': 900000,
    'eastern finlnad': 900000
}
# Print dictionary
print(students_by_regions_finland)

# Sorted by keys
students_by_regions_finland_ascending = dict(
    sorted(students_by_regions_finland.items(), key=lambda dict_item: dict_item))

print(students_by_regions_finland_ascending)


# sort by values
software_dev_salary = {
    'junior_web_developer': 50000,
    'senior_data_scientist': 120000,
    'machine_learning_engineer': 90000,

}

software_dev_salary_sorted_descending = dict(sorted(
    software_dev_salary.items(), key=lambda dict_item: dict_item[1], reverse=True))

print(software_dev_salary)
print(software_dev_salary_sorted_descending)

Output

{'uusimaa': 1000000, 'nothern ostrobothina': 900000, 'eastern finlnad': 900000}
{'eastern finlnad': 900000, 'nothern ostrobothina': 900000, 'uusimaa': 1000000}


{'junior_web_developer': 50000, 'senior_data_scientist': 120000, 'machine_learning_engineer': 90000}
{'senior_data_scientist': 120000, 'machine_learning_engineer': 90000, 'junior_web_developer': 50000}

Now lets break down the code to understand whats going on?

sorted( software_dev_salary.items(), key=lambda dict_item: dict_item[1], reverse=True)

1. software_dev_salary.items() returns a list consisting of a tuple of key and value pair. Its looks like a list but the type is class dict_items.

2.key=lambda dict_item: dict_item[1], tells the access tuple(dict_item) in the list returned by previous code and sort by second item (dict_item[1]) which is value, usedict_item[0] for keys.

3. reverse= True, means descending order and vice-versa.

4.sorted( software_dev_salary.items(), key=lambda dict_item: dict_item[1], reverse=True), combined together it returns list of sorted key-value pair tuple

5. dict(sorted(…)), wrapping with dict convert them items into dictionary.

BTW, the same logic can be used to get max and min key-value pairs. But instead of sorted you’re gonna use max() and min() respectively. max(software_dev_salary.items(), key = lambda dict_item: dict_item[1]). Can you explain what’s going on in the code?

7. How to merge dictionary?

Python dictionary can be merger as {**dict_1, **dict_2, …,**dict_n}. For python 3.9+ its can be merged using “|” operator.

# Merge Dictionary
dict_1 = {'name': 'Harry', 'age': 27, 'location': 'Helsinki'}
dict_2 = {'job': 'Architect'}

# Merge dict using ** argument
dict_merged_1 = {**dict_1, **dict_2}
print(dict_merged_1)

# Python 3.9 has new feature merge "|" operator
dict_merged_2 = dict_1 | dict_2
print(dict_merged_2)

Output

{'name': 'Harry', 'age': 27, 'location': 'Helsinki', 'job': 'Architect'}
{'name': 'Harry', 'age': 27, 'location': 'Helsinki', 'job': 'Architect'}

9. How to convert list to a dictionary?

So, as you know dictionary has key and value pair but the list does not. So, some cases of converting lists into dictionaries are.

9.1 In case of one list.

Use the list items as keys and then provide values some way.

## List to dictionary
pets= ['dog','cat','guinea pig', 'parrot']

# add one value to all
pets_owner ={animal:'Jackson' for animal in pets}
print(pets_owner)

Output

{'dog': 'Jackson', 'cat': 'Jackson', 'guinea pig': 'Jackson', 'parrot': 'Jackson'}

9.2 For loop and Zip with two lists.

## List to dictionary
pets= ['dog','cat','guinea pig', 'parrot']

# Adding two list using zip and for loops
numbers =  [2,4,10,2]
pet_number_dict={}

for animal,num in zip(pets,numbers):
    pet_number_dict[animal]= num

print(pet_number_dict)

Output

{'dog': 2, 'cat': 4, 'guinea pig': 10, 'parrot': 2}

9.3 Zip, Comprehension with two lists.

## List to dictionary
pets= ['dog','cat','guinea pig', 'parrot']

# Add different values  using zip  and comprehension
pet_number_dict_2 = {animal:num for animal,num in zip(pets,numbers)}

print(pet_number_dict_2)

Output

{'dog': 2, 'cat': 4, 'guinea pig': 10, 'parrot': 2}

10. Whats the difference between duplicating dictionary with and without copy()?

What the question means is dict_2 = dict_1 vs. dict_2 = dict_1.copy(). When you are duplicating a dictionary object without a copy() method, you are not creating a new dictionary but pointing to the same dictionary object. So, when you make changes in the duplicate dictionary it changes the original one too.

# Duplicating dict with and without copy
to_buy_list = {
    'eggs': '1 karton',
    'banana': '1 kg',
    'milk': '1 ltr',
    'sugar': '1 kg'

}
print("Original List before {}".format(to_buy_list))

# Lets duplicate without copy
to_buy_list_2 = to_buy_list

# Lets make change to duplicate list
to_buy_list_2['salt'] = '1 kg'

print("Original List after duplication {}".format(to_buy_list))

print("Are the memory address of two dicts same? {}".format(
    id(to_buy_list) == id(to_buy_list_2)))

Output

Original List before {'eggs': '1 karton', 'banana': '1 kg', 'milk': '1 ltr', 'sugar': '1 kg'}

Original List after duplication {'eggs': '1 karton', 'banana': '1 kg', 'milk': '1 ltr', 'sugar': '1 kg', 'salt': '1 kg'}

Are the memory address of two dicts same? True

Now lets do all that with copy() method.

# Duplicating dict with and without copy
to_buy_list = {
    'eggs': '1 karton',
    'banana': '1 kg',
    'milk': '1 ltr',
    'sugar': '1 kg'

}
print("Original List before {}".format(to_buy_list))

# Lets duplicate without copy
to_buy_list_2 = to_buy_list.copy()

# Lets make change to duplicate list
to_buy_list_2['salt'] = '1 kg'

print("Original List after duplication {}".format(to_buy_list))

print("Are the memory address of two dicts same? {}".format(
    id(to_buy_list) == id(to_buy_list_2)))


Output

Original List before {'eggs': '1 karton', 'banana': '1 kg', 'milk': '1 ltr', 'sugar': '1 kg'}

Original List after duplication {'eggs': '1 karton', 'banana': '1 kg', 'milk': '1 ltr', 'sugar': '1 kg'}

Are the memory address of two dicts same? False

These were a few faqs on python dictionaries. I hope I was clear and but please do give a like and follow me for more. Give me feedback on the comment section. Find the zip file download below for more practice exercise of python dictionary.

Leave a Reply

%d bloggers like this: