[python] – Dictionary

by | Feb 4, 2024 | Ngôn ngữ lập trình, Python | 0 comments

This Python dictionary exercise aims to help Python developers to learn and practice dictionary operations. All questions are tested on Python 3.

Python dictionary is a mutable object, and it contains the data in the form of key-value pairs. Each key is separated from its value by a colon (:).

Dictionary is the most widely used data structure, and it is necessary to understand its methods and operations.

This Python dictionary exercise includes the following: –

  • It contains 10 dictionary questions and solutions provided for each question.
  • Practice different dictionary assignments, programs, and challenges.

It covers questions on the following topics:

  • Dictionary operations and manipulations
  • Dictionary functions
  • Dictionary comprehension

Exercise 1: Convert two lists into a dictionary

There are the two lists. Write a Python program to convert them into a dictionary in a way that item from list1 is the key and item from list2 is the values.

Example

Input

keys = ['Ten', 'Twenty', 'Thirty']
values = [10, 20, 30]

Output

{'Ten': 10, 'Twenty': 20, 'Thirty': 30}

Hint:

  • Use the zip() function. This function takes two or more iterables (like list, dict, string), aggregates them in a tuple, and returns it.
  • Or, Iterate the list using a for loop and range() function. In each iteration, add a new key-value pair to a dict using the update() method

Solution:

Solution 1: The zip() function and a dict() constructor

  • Use the zip(keys, values) to aggregate two lists.
  • Wrap the result of a zip() function into a dict() constructor.
keys = ['Ten', 'Twenty', 'Thirty']
values = [10, 20, 30]

res_dict = dict(zip(keys, values))
print(res_dict)

Solution 2: Using a loop and update() method of a dictionary

keys = ['Ten', 'Twenty', 'Thirty']
values = [10, 20, 30]

# empty dictionary
res_dict = dict()

for i in range(len(keys)):
    res_dict.update({keys[i]: values[i]})
print(res_dict)

Exercise 2: Merge two Python dictionaries into one

Example

Input

dict1 = {'Ten': 10, 'Twenty': 20, 'Thirty': 30}
dict2 = {'Thirty': 30, 'Fourty': 40, 'Fifty': 50}

Output

{'Ten': 10, 'Twenty': 20, 'Thirty': 30, 'Fourty': 40, 'Fifty': 50}

Solution:

#Python 3.5
dict1 = {'Ten': 10, 'Twenty': 20, 'Thirty': 30}
dict2 = {'Thirty': 30, 'Fourty': 40, 'Fifty': 50}

dict3 = {**dict1, **dict2}
print(dict3)
# Another version of Python:
dict1 = {'Ten': 10, 'Twenty': 20, 'Thirty': 30}
dict2 = {'Thirty': 30, 'Fourty': 40, 'Fifty': 50}

dict3 = dict1.copy()
dict3.update(dict2)
print(dict3)

Exercise 3: Print the value of key ‘history’ from the below dict

Example

Input

sampleDict = {
    "class": {
        "student": {
            "name": "Mike",
            "marks": {
                "physics": 70,
                "history": 80
            }
        }
    }
}

Output

80

Hint:

  • It is a nested dict. Use the correct chaining of keys to locate the specified key-value pair.

Solution:

sampleDict = {
    "class": {
        "student": {
            "name": "Mike",
            "marks": {
                "physics": 70,
                "history": 80
            }
        }
    }
}

# understand how to located the nested key
# sampleDict['class'] = {'student': {'name': 'Mike', 'marks': {'physics': 70, 'history': 80}}}
# sampleDict['class']['student'] = {'name': 'Mike', 'marks': {'physics': 70, 'history': 80}}
# sampleDict['class']['student']['marks'] = {'physics': 70, 'history': 80}

# solution
print(sampleDict['class']['student']['marks']['history'])

Exercise 4: Initialize dictionary with default values

In Python, we can initialize the keys with the same values.

Example

Input

employees = ['Kelly', 'Emma']
defaults = {"designation": 'Developer', "salary": 8000}

Output

{'Kelly': {'designation': 'Developer', 'salary': 8000}, 'Emma': {'designation': 'Developer', 'salary': 8000}}

Hint:

  • Use the fromkeys() method of dict.

Solution:

The fromkeys() method returns a dictionary with the specified keys and the specified value.

employees = ['Kelly', 'Emma']
defaults = {"designation": 'Developer', "salary": 8000}

res = dict.fromkeys(employees, defaults)
print(res)

# Individual data
print(res["Kelly"])

Exercise 5: Create a dictionary by extracting the keys from a given dictionary

Write a Python program to create a new dictionary by extracting the mentioned keys from the below dictionary.

Example

Input

sample_dict = {
    "name": "Kelly",
    "age": 25,
    "salary": 8000,
    "city": "New york"}

# Keys to extract
keys = ["name", "salary"]

Output

{'name': 'Kelly', 'salary': 8000}

Hint:

  • Iterate the mentioned keys using a loop
  • Next, check if the current key is present in the dictionary, if it is present, add it to the new dictionary

Solution:

Solution 1: Dictionary Comprehension

sampleDict = { 
  "name": "Kelly",
  "age":25, 
  "salary": 8000, 
  "city": "New york" }

keys = ["name", "salary"]

newDict = {k: sampleDict[k] for k in keys}
print(newDict)

Solution 2: Using the update() method and loop

sample_dict = {
    "name": "Kelly",
    "age": 25,
    "salary": 8000,
    "city": "New york"}

# keys to extract
keys = ["name", "salary"]

# new dict
res = dict()

for k in keys:
    # add current key with its va;ue from sample_dict
    res.update({k: sample_dict[k]})
print(res)

Exercise 6: Delete a list of keys from a dictionary

Example

Input

sample_dict = {
    "name": "Kelly",
    "age": 25,
    "salary": 8000,
    "city": "New york"
}

# Keys to remove
keys = ["name", "salary"]

Output

{'city': 'New york', 'age': 25}

Hint:

  • Iterate the mentioned keys using a loop
  • Next, check if the current key is present in the dictionary, if it is present, remove it from the dictionary
  • To achieve the above result, we can use the dictionary comprehension or the pop() method of a dictionary.

Solution:

Solution 1: Using the pop() method and loop

sample_dict = {
    "name": "Kelly",
    "age": 25,
    "salary": 8000,
    "city": "New york"
}
# Keys to remove
keys = ["name", "salary"]

for k in keys:
    sample_dict.pop(k)
print(sample_dict)

Solution 2: Dictionary Comprehension

sample_dict = {
    "name": "Kelly",
    "age": 25,
    "salary": 8000,
    "city": "New york"
}
# Keys to remove
keys = ["name", "salary"]

sample_dict = {k: sample_dict[k] for k in sample_dict.keys() - keys}
print(sample_dict)

Exercise 7: Check if a value exists in a dictionary

We know how to check if the key exists in a dictionary. Sometimes it is required to check if the given value is present.

Write a Python program to check if value 200 exists in the following dictionary.

Example

Input

sample_dict = {'a': 100, 'b': 200, 'c': 300}

Output

200 present in a dict

Hint:

  • Get all values of a dict in a list using the values() method.
  • Next, use the if condition to check if 200 is present in the given list

Solution:

sample_dict = {'a': 100, 'b': 200, 'c': 300}
if 200 in sample_dict.values():
    print('200 present in a dict')

Exercise 8: Rename key of a dictionary

Write a program to rename a key city to a location in the following dictionary.

Example

Input

sample_dict = {
  "name": "Kelly",
  "age":25,
  "salary": 8000,
  "city": "New york"
}

Output

{'name': 'Kelly', 'age': 25, 'salary': 8000, 'location': 'New york'}

Hint:

  • Remove the city from a given dictionary
  • Add a new key (location) into a dictionary with the same value

Solution:

sample_dict = {
    "name": "Kelly",
    "age": 25,
    "salary": 8000,
    "city": "New york"
}

sample_dict['location'] = sample_dict.pop('city')
print(sample_dict)

Exercise 9: Get the key of a minimum value from the following dictionary

Example

Input

sample_dict = {
  'Physics': 82,
  'Math': 65,
  'history': 75
}

Output

Math

Hint:

  • Use the built-in function min()

Solution:

sample_dict = {
    'Physics': 82,
    'Math': 65,
    'history': 75
}
print(min(sample_dict, key=sample_dict.get))

Exercise 10: Change value of a key in a nested dictionary

Write a Python program to change Brad’s salary to 8500 in the following dictionary.

Example

Input

sample_dict = {
    'emp1': {'name': 'Jhon', 'salary': 7500},
    'emp2': {'name': 'Emma', 'salary': 8000},
    'emp3': {'name': 'Brad', 'salary': 500}
}

Output

{
   'emp1': {'name': 'Jhon', 'salary': 7500},
   'emp2': {'name': 'Emma', 'salary': 8000},
   'emp3': {'name': 'Brad', 'salary': 8500}
}

Solution:

sample_dict = {
    'emp1': {'name': 'Jhon', 'salary': 7500},
    'emp2': {'name': 'Emma', 'salary': 8000},
    'emp3': {'name': 'Brad', 'salary': 6500}
}

sample_dict['emp3']['salary'] = 8500
print(sample_dict)