Python Dictionary Practice Programs For Beginners

# Python Dictionary Practice Programs For Beginners

clickHere
Updated on Nov 25, 2022 19:24 IST

Working with Python dictionary types can seem slightly difficult if you are not familiar with its features. The best way to master it is by solving problem statements. It is best if you try to code by yourself before trying to view the solutions given below. Also, there are plenty of ways to achieve what you want in Python. Take the initiative to explore new ways to solve the problem statements given below.

All right! Let’s get started!

## Check if a Given Key Already Exists in Dictionary

Let’s begin with a simple question. If you have learned about Python dictionaries, you will know that you can check if a given key exists or not in multiple ways. Here’s one of them.

```#Creating a Dictionary
D1 = {'first_name' : 'Jim', 'age' : 23, 'height' : 6.0 , 'job' : 'developer', 'company': 'XYZ'}

def check_key(x):
if x in D1:
return 'Yes'
else:
return 'No'
print("Is key named 'first_name' present?", check_key('first_name'))
print("Is key named 'jobs' present?", check_key('jobs'))
```

## Handle Missing Keys in Dictionary

Dictionary is a collection in python, where the data is stored in the form of a key-value pair, that is, it maps key to its value. Often, you will not know all the keys present in the dictionary and you might end up with a typing error which may lead to runtime error due to missing keys in the dictionary. So, how to deal with such situations?

Here’s one way!

```#Handle Missing Keys in Dictionary: Using get() function
D1 = {'first_name' : 'Jim', 'age' : 23, 'height' : 6.0 , 'job' : 'developer', 'company': 'XYZ'}

#fetch a value of dict by its key using get(key, default)
print(D1.get('name', 'Not present'))
print(D1.get('first_name', 'Not present'))

```

The get(key, default_value) is a built-in function that you can use to reduce multiple lines of code. It checks if the key is present, if not returns the value that is passed to default_value argument.

## Extract Unique Values in a Given Dictionary

In a dictionary, the keys have to be unique, whereas the values can be duplicated. So, given a dictionary as shown below, how can you print all the unique values it has?

```D1 = {'list1': [4, 7, 10, 20],
'list2': [7, 16, 9, 10],
'list3': [13, 10, 4, 8],
'list4': [7, 20, 6, 11]}
Output = [4, 6, 7, 8, 9, 10, 11, 13, 16, 20]

#Extract unique values in dictionary
#Initializing Dictionary
D1 = {'list1': [4, 7, 10, 20],
'list2': [7, 16, 9, 10],
'list3': [13, 10, 4, 8],
'list4': [7, 20, 6, 11]}

#Actual dictionary
print("The given dictionary is:", str(D1))

#Extract the sorted unique values using set_comprehension + values() + sorted()
uniqueVals = list(sorted({val2 for val1 in D1.values() for val2 in val1 }))

#list of unique values
print("The unique values of the given dictionary are:", uniqueVals)
```

You need to create a list which has the sum of key-value pairs of a given dictionary. This can be done using a for loop and append() function.

```#Print sum of key-value pairs

D1 = {2: 8, 5: 20, 3: 15}
res_sumList = []

# Traverse the dictionary
for key in D1:
res_sumList.append(key + D1[key])

# Print the list
print("Sum of Key-value pairs is =",list(res_sumList))
```

## Replace Dictionary Values From Other Dictionary

Let’s say you are given two dictionaries. You need to write a python program that will replace the values in the first dictionary with the values from the second dictionary if the key is present in the second dictionary.

You can do this using dictionary comprehension or using loops. Here’s how you can do by using loops

```#Replace values in dict1 from dict2, if key is present in dict2 - Using loops

# initializing D1 - first dictionary
D1 = {'first_name' : 'Jim', 'age' : 23, 'height' : 6.0 , 'job' : 'developer', 'company': 'XYZ'}

# initializing D2 - - first dictionary
D2 = {'age' : 35, 'job' : 'senior data analyst'}

for key in D1:

# checking if key present in dict2
if key in D2:
D1[key] = D2[key]

# printing the details
print("The original dictionary: " + str(D1))
print("The updated dictionary: " + str(D2))
```

## Update or Change the Keys in a Given Dictionary

.You can do this in multiple ways as mentioned below:

1. Using assignment operator
2. Using pop() method
3. Using zip() method
```#changing the keys of dictionary

D1 = {'jim': 23, 'sam': 29, 'dean': 33, 'micheal': 40}

#print the original dictionary
print("The original dictionary is =", D1)

#using assignment (basic technique)
#changing key 'jim' to 'sam'
D1['sam'] = D1['jim']
del D1['jim']
# printing result
print ("Dictionary D1 after changing key 'jim'=", str(D1))

#using pop() function
#changing key 'sam' to 'anni'
D1['anni'] = D1.pop('sam')
# printing result
print ("Dictionary D1 after changing key 'sam'=", str(D1))

#To change all the keys
#use zip()
new_keyslist = ['tom', 'simon', 'tony', 'roy']
final_D1 = dict(zip(new_keyslist, list(D1.values())))
# printing result
print ("Dictionary D1 after changing all keys=", str(final_D1))
```

## Delete a List of Keys in a Given Dictionary

You can do this using the pop() method or using dictionary comprehension. Here’s the solution using the pop() method.

```#deleting list of keys of dictionary
D1 = {'jim': 23, 'sam': 29, 'dean': 33, 'micheal': 40}

# Keys to remove
keys = ["jim", "sam"]

for k in keys:
D1.pop(k)
print(D1)
```

## Count the Frequency of List Items Using a Dictionary

You can solve this in many ways. Any ideas? Well, you can just use looping constructs or use the list() count method or you can start with an empty dictionary and use the dict.get() method. Probably many other ways!

Here’s how to achieve it using the dict.get() method.

```#count the frequency of list item and
#print them in the form [list item: frequency]
List1 = [1, 2, 2, 3, 4, 1, 4, 5, 5, 6, 7, 7]

def CountOccur(test_list):

# create an empty dictionary
res_dict = {}
for i in test_list:
res_dict[i] = res_dict.get(i, 0) + 1
return res_dict

# Driver function
if __name__ == "__main__":
print(CountOccur(List1))

```

## Change the Value of a Key in Nested Dictionary

Given a nested dictionary, you need to write a program demonstrating how to change the value associated with a particular key of that dictionary.

```#change the value of a key in nested dictionary
#Initializing Dictionary
D1 = {'emp1': {'name' : 'Jim', 'age' : 26, 'job' : 'developer'},
'emp2': {'name' : 'Sam', 'age' : 30, 'job' : 'data analyst'},
'emp3': {'name' : 'Dean', 'age' : 29, 'job' : 'data scientist'},
'emp4': {'name' : 'Leo', 'age' : 25, 'job' : 'python developer'}}

#Actual dictionary
print("The actual dictionary is:", D1)
#Change the value of a dictionary
D1['emp3']['age'] = 24
#Updated dictionary
print("The updated dictionary is:", D1)
```

## Map Two Lists Into A Dictionary

You can use the zip(iterator1, iterator2, iterator3, …) function to map the given lists. This function returns a zip object, where the the first item of each iterator are mapped together, similarly the second item of each iterator are mapped together, and so on.

```#map to given lists into a dictionary
keys = ['first_name', 'age' , 'job', 'company']
values = ['Jim', 23, 'developer', 'XYZ']

#map using zip()
D1 = dict(zip(keys, values))
print(D1)
```

## Check if the Given Dictionary Is Empty or Not

One way to check this using the len() function, which you can try coding. In this article, we will achieve this using the bool() function. The bool() function evaluates to standard true or false and is used to return or convert a value to Boolean type. If you pass an empty dictionary, the bool() evaluates to False, as failure to convert something that is empty.

```#check if the dictionary is empty or not using bool()
#Initializing Dictionary
D1 = {}

#Actual dictionary
print("The actual dictionary is:", str(D1))

#checking if empty or not
result = not bool(D1)
print("Is the given dictionary empty? :", result)
```

## Get Keys with Maximum and Minimum Value in a Dictionary

We are going to use max(n1, n2, n3, …[, key=func]) and min(n1, n2, n3, …[, key=func]) functions and assign a lambda function to the ‘key’ parameter to check for max and min values.

```#get keys with max and min values
# Dictionary Initialization
D1 = {'Jim': 23, 'Sam': 29, 'Dean': 33, 'Micheal': 40}

# Python code to find key with Maximum value in Dictionary
Key_max = max(D1, key= lambda x: D1[x])
Key_min = min(D1, key= lambda x: D1[x])
print("The key with maximum value:", Key_max, ",& corresponding value:", D1[Key_max])
print("The key with minimum value:", Key_min, ",& corresponding value:", D1[Key_min])
```

## Check if the Substring Matches Any Key in a Dictionary

Often you might just know a specific part of the key and using this you have to fetch the associated value. So, you need to check if there exists any key which has the substring that you are searching for. If yes, then print the values associated with those keys. This can be achieved in multiple ways.

Let’s learn how to do this using dict(), filter(), and lambda function. First create a lambda function that checks if the given substring is present in any of the dictionary keys. Then pass this lambda function as a parameter of filter() function, which checks if the given function is true for each value of the sequence. Then use the dict() function to print the filtered key value pairs as a new dictionary.

```#Check if the Substring Matches Any Key in a Dictionary
# Dictionary Initialization
D1 = {'Jim': 23, 'Sam Winchester': 29, 'Dean Winchester': 33, 'Micheal': 40}

#search substring
search_string = "Winchester"
#Actual dictionary
print("The actual dictionary is:", str(D1))

res_string = dict(filter(lambda item: search_string in item[0], D1.items()))

#Resultant dictionary
print("The Key-Value pair for search keys ::", str(res_string))
```

## Get a Key From Value in a Dictionary

You need to write a program, which returns the key for a given value. This can be done in multiple ways. Let’s try doing it using dict.items() function.

```#get key for a given value using dict.items()
# Dictionary Initialization
D1 = {'Jim': 23, 'Sam Winchester': 29, 'Dean Winchester': 45, 'Micheal': 40}

def getKey(dict_val):
for dict_key, value in D1.items():
if dict_val == value:
return dict_key
return "key doesn't exist"

print("Get key of value 40:", getKey(40))
print("Get key of value 20:", getKey(20))
```

Here, the getKey function takes an argument and checks if the particular value is present in the list of dictionary values. If the value is present, then the key is printed, else a default message is displayed.

## Sort a Given Dictionary by Key

You need to write a program that will sort the dictionary based on the key. Taking keys type as string, the string takes place in lexicographical order.

Here’s the code!

```#sort a dictionary by key
# Dictionary Initialization
D1 = {'Jim': 23, 'Jerry': 29, 'Micheal': 40, 'Merlin': 45, 'Antony': 34}

res_dict = sorted(D1.items())
print(res_dict)
```

The dict.items() method returns a dict_items object containing the key-value pairs of the D1 dictionary. Then the sorted() method sorts the dictionary based on the keys.

That’s it, guys! Hope this article was informative. However, to master the basics it’s best you practice by taking up some challenging problem statements and try writing the code. If you have any queries, let us know in the comment section.

Recently completed any professional course/certification from the market? Tell us what you liked or disliked in the course for more curated content.