lecture-5-dictionary
April 11, 2024
1 Python Dictionary
Difficulty Level : Easy Last Updated : 31 Oct, 2021 Dictionary in Python is an unordered collection
of data values, used to store data values like a map, which, unlike other Data Types that hold only a
single value as an element, Dictionary holds key:value pair. Key-value is provided in the dictionary
to make it more optimized.
2 Creating a Dictionary
In Python, a Dictionary can be created by placing a sequence of elements within curly {} braces,
separated by ‘comma’. Dictionary holds pairs of values, one being the Key and the other corre-
sponding pair element being its Key:value. Values in a dictionary can be of any data type and can
be duplicated, whereas keys can’t be repeated and must be immutable.
[11]: # Creating a Dictionary
# with Integer Keys
List = [1, 3, 'as', 56]
Dict = {1: 'A', 2: 'For', 3: 'B'}
print("\nDictionary with the use of Integer Keys: ")
print(Dict)
print(Dict.values())
print(Dict.keys())
Dictionary with the use of Integer Keys:
{1: 'A', 2: 'For', 3: 'B'}
dict_values(['A', 'For', 'B'])
dict_keys([1, 2, 3])
[12]: # Creating a Dictionary
# with Mixed keys
Dict = {'Name': ['Ali','ahmed', 'shoib'] , 'roll no' : [1, 23, 12]}
print("\nDictionary with the use of Mixed Keys: ")
print(Dict)
1
Dictionary with the use of Mixed Keys:
{'Name': ['Ali', 'ahmed', 'shoib'], 'roll no': [1, 23, 12]}
[13]: # Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
# Creating a Dictionary
# with dict() method
Dict = dict({1: 'BSAI', 2: 'For', 3:'AI'})
print("\nDictionary with the use of dict(): ")
print(Dict)
# Creating a Dictionary
# with each item as a Pair
Dict = dict([(1, 'BSAI'), (2, 'For')])
print("\nDictionary with each item as a pair: ")
print(Dict)
Empty Dictionary:
{}
Dictionary with the use of dict():
{1: 'BSAI', 2: 'For', 3: 'AI'}
Dictionary with each item as a pair:
{1: 'BSAI', 2: 'For'}
3 Adding elements to a Dictionary
In Python Dictionary, the Addition of elements can be done in multiple ways. One value at a
time can be added to a Dictionary by defining value along with the key e.g. Dict[Key] = ‘Value’.
Updating an existing value in a Dictionary can be done by using the built-in update() method.
Nested key values can also be added to an existing Dictionary.
[15]: # Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
# Adding elements one at a time
Dict[0] = 'AI'
Dict[2] = 'For'
Dict[3] = 1
print("\nDictionary after adding 3 elements: ")
2
print(Dict)
# Adding set of values
# to a single Key
Dict['Value_set'] = 2, 3, 4
print("\nDictionary after adding 3 elements: ")
print(Dict)
# Updating existing Key's Value
Dict[2] = 'Welcome'
print("\nUpdated key value: ")
print(Dict)
# Adding Nested Key value to Dictionary
Dict[5] = {'Nested' :{1 : 'Life', 2 : 'BSAI'}}
print("\nAdding a Nested Key: ")
print(Dict)
Empty Dictionary:
{}
Dictionary after adding 3 elements:
{0: 'AI', 2: 'For', 3: 1}
Dictionary after adding 3 elements:
{0: 'AI', 2: 'For', 3: 1, 'Value_set': (2, 3, 4)}
Updated key value:
{0: 'AI', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4)}
Adding a Nested Key:
{0: 'AI', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4), 5: {'Nested': {1: 'Life',
2: 'BSAI'}}}
4 Accessing elements from a Dictionary
In order to access the items of a dictionary refer to its key name. Key can be used inside square
brackets.
[15]: # Python program to demonstrate
# accessing a element from a Dictionary
# Creating a Dictionary
Dict = {1: 'BSAI', 'name': 'For', 3: 'AI'}
# accessing a element using key
print("Accessing a element using key:")
3
print(Dict['name'])
# accessing a element using key
print("Accessing a element using key:")
print(Dict[1])
Accessing a element using key:
For
Accessing a element using key:
BSAI
[16]: # Creating a Dictionary
Dict = {1: 'AI', 'name': 'For', 3: 'BSAI'}
# accessing a element using get()
# method
print("Accessing a element using get:")
print(Dict.get(3))
Accessing a element using get:
BSAI
5 Accessing an element of a nested dictionary
In order to access the value of any key in the nested dictionary, use indexing [] syntax.
[17]: # Creating a Dictionary
Dict = {'Dict1': {1: 'AI'},
'Dict2': {'Name': 'For'}}
# Accessing element using key
print(Dict['Dict1'])
print(Dict['Dict1'][1])
print(Dict['Dict2']['Name'])
{1: 'AI'}
AI
For
[15]: myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004
},
"child2" : {
"name" : "Tobias",
"year" : 2007
4
},
"child3" : {
"name" : "Linus",
"year" : 2011
}
}
[22]: child1 = {
"name" : "Emil",
"year" : 2004
}
child2 = {
"name" : "Tobias",
"year" : 2007
}
child3 = {
"name" : "Linus",
"year" : 2011
}
myfamily = {
"child1" : child1,
"child2" : child2,
"child3" : child3
}
myfamily
[22]: {'child1': {'name': 'Emil', 'year': 2004},
'child2': {'name': 'Tobias', 'year': 2007},
'child3': {'name': 'Linus', 'year': 2011}}
6 Removing Elements from Dictionary
6.1 Using del keyword
In Python Dictionary, deletion of keys can be done by using the del keyword. Using the del keyword,
specific values from a dictionary as well as the whole dictionary can be deleted. Items in a Nested
dictionary can also be deleted by using the del keyword and providing a specific nested key and
particular key to be deleted from that nested Dictionary.
[18]: # Initial Dictionary
Dict = { 5 : 'Welcome', 6 : 'To', 7 : 'BSAI',
'A' : {1 : 'BSAI', 2 : 'For', 3 : 'AI'},
'B' : {1 : 'Amazing', 2 : 'Life'}}
print("Initial Dictionary: ")
print(Dict)
5
# Deleting a Key value
del Dict[6]
print("\nDeleting a specific key: ")
print(Dict)
# Deleting a Key from
# Nested Dictionary
del Dict['A'][2]
print("\nDeleting a key from Nested Dictionary: ")
print(Dict)
Initial Dictionary:
{5: 'Welcome', 6: 'To', 7: 'BSAI', 'A': {1: 'BSAI', 2: 'For', 3: 'AI'}, 'B': {1:
'Amazing', 2: 'Life'}}
Deleting a specific key:
{5: 'Welcome', 7: 'BSAI', 'A': {1: 'BSAI', 2: 'For', 3: 'AI'}, 'B': {1:
'Amazing', 2: 'Life'}}
Deleting a key from Nested Dictionary:
{5: 'Welcome', 7: 'BSAI', 'A': {1: 'BSAI', 3: 'AI'}, 'B': {1: 'Amazing', 2:
'Life'}}
7 Using pop() method
Pop() method is used to return and delete the value of the key specified.
[2]: # Creating a Dictionary
Dict1 = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}
# Deleting a key
# using pop() method
pop_ele = Dict1.pop(1)
print('\nDictionary after deletion: ' + str(Dict1))
print('Value associated to poped key is: ' + str(pop_ele))
Dictionary after deletion: {'name': 'For', 3: 'Geeks'}
Value associated to poped key is: Geeks
8 Using popitem() method
The popitem() returns and removes an arbitrary element (key, value) pair from the dictionary.
[4]: # Creating Dictionary
Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}
6
# Deleting an arbitrary key
# using popitem() function
pop_ele = Dict.popitem()
print("\nDictionary after deletion: " + str(Dict))
print("The arbitrary pair returned is: " + str(pop_ele))
Dictionary after deletion: {1: 'Geeks', 'name': 'For'}
The arbitrary pair returned is: (3, 'Geeks')
9 Using clear() method
All the items from a dictionary can be deleted at once by using clear() method.
[1]: # Creating a Dictionary
Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}
# Deleting entire Dictionary
Dict.clear()
print("\nDeleting Entire Dictionary: ")
print(Dict)
Deleting Entire Dictionary:
{1: 'Geeks', 'name': 'For', 3: 'Geeks'}
10 Built in Function
[8]: str(Dict)
[8]: "{1: 'Geeks', 'name': 'For'}"
[9]: len(Dict)
[9]: 2
[10]: type(Dict)
[10]: dict
[11]: Dict.clear()
[12]: Dict.copy()
[12]: {}
7
[3]: Dict.fromkeys()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-3-0daed0f5138e> in <module>
----> 1 Dict.fromkeys()
TypeError: fromkeys expected at least 1 arguments, got 0
[17]: from IPython.display import display, Image
display(Image(filename='dictionary methods.png'))
[18]: x = ('key1', 'key2', 'key3')
y = 0
thisdict = dict.fromkeys(x, y)
print(thisdict)
{'key1': 0, 'key2': 0, 'key3': 0}
[19]: x = ('key1', 'key2', 'key3')
thisdict = dict.fromkeys(x)
8
print(thisdict)
{'key1': None, 'key2': None, 'key3': None}
[20]: car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.items()
print(x)
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])
[2]: car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"persons": {'Ali':2, "ahmed": 3, 'bilal':4}
x = car.items()
car["year"] = 2018
print(x)
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 2018), ('persons',
{'Ali': 2, 'ahmed': 3, 'bilal': 4})])
[ ]: car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"persons": {'Ali':2, "ahmed": 3, 'bilal':4}
# car = ["a", "b" , "c"]
for i,j in car.items():
9
print(i)
print(j)
10.1 Question: Count the occurrence of each unique value in a dictionary.
[2]: # Dictionary
my_dict = {'a': 1, 'b': 2, 'c': 1, 'd': 2}
# Count occurrence of each value
occurrence_count = {}
for value in my_dict.values():
occurrence_count[value] = occurrence_count.get(value, 0) + 1
# Print the occurrence count
print("Occurrence count of each unique value:", occurrence_count)
Occurrence count of each unique value: {1: 2, 2: 2}
10.2 Question: Calculate the sum of all values in a dictionary.
[3]: # Dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3}
# Calculate the sum of values
sum_of_values = sum(my_dict.values())
# Print the sum
print("Sum of all values in the dictionary:", sum_of_values)
Sum of all values in the dictionary: 6
10.3 Question: Get the keys of a dictionary as a list.
[4]: # Dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3}
# Get the keys as a list
keys_list = list(my_dict.keys())
# Print the keys list
print("Keys of the dictionary:", keys_list)
Keys of the dictionary: ['a', 'b', 'c']
10
10.4 Question: Check if a value exists in a dictionary.
[5]: # Dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3}
value_to_check = 2
# Check if the value exists
if value_to_check in my_dict.values():
print("Value '{}' exists in the dictionary.".format(value_to_check))
else:
print("Value '{}' does not exist in the dictionary.".format(value_to_check))
Value '2' exists in the dictionary.
10.5 Question: Find the key with the maximum value in a dictionary.
[6]: # Dictionary
my_dict = {'a': 10, 'b': 20, 'c': 30}
# Find the key with the maximum value
max_key = max(my_dict, key=my_dict.get)
# Print the key with the maximum value
print("Key with the maximum value:", max_key)
Key with the maximum value: c
10.6 Question: Merge two dictionaries.
[7]: # Dictionaries
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
# Merge the dictionaries
merged_dict = {**dict1, **dict2}
# Print the merged dictionary
print("Merged dictionary:", merged_dict)
Merged dictionary: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
10.7 Question: Remove a key-value pair from a dictionary.
[8]: # Dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3}
key_to_remove = 'b'
# Remove the key-value pair
11
my_dict.pop(key_to_remove, None)
# Print the updated dictionary
print("Dictionary after removing key '{}':".format(key_to_remove), my_dict)
Dictionary after removing key 'b': {'a': 1, 'c': 3}
10.8 Question: Get the value corresponding to a specific key in a dictionary.
[10]: # Dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3}
key_to_get = 'b'
# Get the value corresponding to the key
value = my_dict.get(key_to_get)
# Print the value
print("Value corresponding to key '{}':".format(key_to_get), value)
Value corresponding to key 'b': 2
11 Question: Check if a key exists in a dictionary.
[11]: # Dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3}
key_to_check = 'b'
# Check if the key exists
if key_to_check in my_dict:
print("Key '{}' exists in the dictionary.".format(key_to_check))
else:
print("Key '{}' does not exist in the dictionary.".format(key_to_check))
Key 'b' exists in the dictionary.
11.1 Question: Find the length of a dictionary.
[12]: # Dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3}
# Calculate the length of the dictionary
length = len(my_dict)
# Print the length
print("Length of the dictionary:", length)
Length of the dictionary: 3
12