DEV Community

Cover image for Python Developer Interview Questions: Dictionaries
Nibesh Khadka
Nibesh Khadka

Posted on

Python Developer Interview Questions: Dictionaries

Hello and welcome to this blog. I am Nibesh Khadka from Khadka's Coding Lounge. I have written a short blog on frequent questions on python dictionaries.

What is a 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 separated 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 IDs, 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'])


Enter fullscreen mode Exit fullscreen mode


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


Enter fullscreen mode Exit fullscreen mode

How do I get the keys to the dictionary?

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



print(user_info.keys())


Enter fullscreen mode Exit fullscreen mode


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


Enter fullscreen mode Exit fullscreen mode

How do I get the values of the dictionary?

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



print(user_info.values())


Enter fullscreen mode Exit fullscreen mode


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



Enter fullscreen mode Exit fullscreen mode

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

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



print(user_info.items())


Enter fullscreen mode Exit fullscreen mode


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


Enter fullscreen mode Exit fullscreen mode

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

You can use the if statement within to check if the key exists.



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


Enter fullscreen mode Exit fullscreen mode


##Output
Nibesh


Enter fullscreen mode Exit fullscreen mode

Are dictionaries mutable?

Yes, the Python dictionary is a mutable object. This means 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)



Enter fullscreen mode Exit fullscreen mode


#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'}


Enter fullscreen mode Exit fullscreen mode

Is it possible to find the length of a dictionary?

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



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


Enter fullscreen mode Exit fullscreen mode


# Output
5


Enter fullscreen mode Exit fullscreen mode

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

The pop() method in the list can remove 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)


Enter fullscreen mode Exit fullscreen mode


#Output

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

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


Enter fullscreen mode Exit fullscreen mode

How to access items in nested dictionary items

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



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

# Accessing Dictionary inside the 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 the list inside the dictionary
# Lest access the last item in the list

print(subject_info['Science Topics'][-1])


Enter fullscreen mode Exit fullscreen mode


#Output

Male

Biology


Enter fullscreen mode Exit fullscreen mode

How to sort dictionary keys and values?

Dictionary items can be sorted by both keys and values.



# Sort dictionary
students_by_regions_finland = {
'uusimaa': 1000000,
'nothern ostrobothina': 900000,
'eastern finlnad': 900000
}

# Print dictionary
print(students_by_regions_finland)

# Sort 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)



Enter fullscreen mode Exit fullscreen mode


#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}


Enter fullscreen mode Exit fullscreen mode

Now let’s break down the code to understand what's going on?



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


Enter fullscreen mode Exit fullscreen mode
  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, use dict_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 their items into the 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?

How to merge dictionaries?

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)


Enter fullscreen mode Exit fullscreen mode


#Output

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

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


Enter fullscreen mode Exit fullscreen mode

How to convert a list into a dictionary?

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

In the case of one list

Use the list items like keys and then provide values in 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)


Enter fullscreen mode Exit fullscreen mode


#Output

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


Enter fullscreen mode Exit fullscreen mode

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)


Enter fullscreen mode Exit fullscreen mode


#Output

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


Enter fullscreen mode Exit fullscreen mode

Using 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)


Enter fullscreen mode Exit fullscreen mode


#Output

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


Enter fullscreen mode Exit fullscreen mode

What is the difference between duplicating a dictionary with and without a 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 list 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)))


Enter fullscreen mode Exit fullscreen mode


#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 the same? True


Enter fullscreen mode Exit fullscreen mode

Now let’s do all that with the 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)))


Enter fullscreen mode Exit fullscreen mode


#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 the same? False


Enter fullscreen mode Exit fullscreen mode

KCL

These were a few FAQs on Python dictionaries. I hope it was worth your time. If you like the blog don't forget to show support by liking it and subscribing to the publication. This was Nibesh Khadka from Khadka's Coding Lounge.

Like and Subscribe

Top comments (0)