Python Dictionaries
A Python dictionary is a data structure that stores items in the form of key-value pairs. The keys are unique and can only be string, numbers or tuples. Values can be changed at any time and can be any data type.
Initializing dictionary
Place key:values pairs inside curly brackets separated by comma.
Syntax: dictionary = { Key1 : Value1, Key2 : Value2.... }
##Initialize some dictionaries
dict1 = {} #Empty dictionary
d_name_age = {'Jenny' : 20, 'Ronin' : 35} #Person's name : person's age
print(dict1)
: {}
print(d_name_age )
: {'Jenny' : 20, 'Ronin' : 35}
--------------------------------------------------------------------------
##Check the data type
print(type(dict1))
: <class 'dict'>
print(type(d_name_age))
: <class 'dict'>
--------------------------------------------------------------------------
##Update a value of the dictionary
d_name_age['Jenny'] = 22
print(d_name_age)
: {'Jenny' : 22, 'Ronin' : 35}
--------------------------------------------------------------------------
##Add a new key-value pair to the dictionary
d_name_age['Martha'] = 32
print(d_name_age)
: {'Jenny' : 22, 'Ronin' : 35, 'Martha' : 32}
How to access values of a dictionary
We have two options:
1- value = dictionary[key]
2- value = dictionary.get(key, "message to display if key is not found")
Both approaches are valid but with the syntax dictionary[key], Python will throw an error (thus stopping the whole program) if the key is not present in the dictionary.
##Initialize some dictionaries
d_name_age = {'Jenny' : 20, 'Ronin' : 35} #Person's name : person's age
--------------------------------------------------------------------------
##Access Jenny's age with dictionary[key]:
Jenny_age = d_name_age['Jenny']
print(Jenny_age)
: 20
##Access value of a non-existent key with dictionary[key]:
stranger_age = d_name_age['Mario']
: KeyError: 'Mario'
##Access Jenny's age with get():
Jenny_age = d_name_age.get('Jenny', 'Name not found')
print(Jenny_age)
: 20
##Access value of a non-existent key with get():
stranger_age = d_name_age.get('Mario', 'Name not found')
print(stranger_age )
: 'Name not found'
Common methods with Python dictionaries
##Initialize a dictionary
d_name_age = {'Jenny' : 20, 'Ronin' : 35}
--------------------------------------------------------------------------
##Length of a dictionary = number of key-value pairs --> len()
num_kv_pairs= len(d_name_age)
print(num_kv_pairs)
: 2
--------------------------------------------------------------------------
##To collect all keys of the dictionary --> keys()
keys = d_name_age.keys()
print(keys)
: dict_keys(['Jenny', 'Ronin'])
#The result is a dictionary keys object which is not subscriptable. #We can convert the output to a list as follows:
keys = list(d_name_age.keys()) #Note the list method
print(keys)
: ['Jenny', 'Ronin']
#With the keys collected inside a list we can do this:
print(keys[0])
: 'Jenny'
--------------------------------------------------------------------------
##To collect all values of the dictionary --> values()
values = d_name_age.values()
print(values)
: dict_values([20, 35])
#The result is a dictionary values object which is also not subscriptable. #We can convert the output to a list as follows:
values = list(d_name_age.values()) #Note the list method
print(values)
: [20, 35]
--------------------------------------------------------------------------
##To collect the key-value pairs --> items()
k_v_pairs = d_name_age.items()
print(k_v_pairs )
: dict_items([('Jenny', 20), ('Ronin', 35)])
#The result is a dictionary items object which can be converted to a list
k_v_pairs = list(d_name_age.items()) #Note the list method
print(k_v_pairs)
: [('Jenny', 20), ('Ronin', 35)] #The result is a list of tuples
--------------------------------------------------------------------------
##To update a dictionary --> update()
#Let's create two dictionaries
dict1 = {'Jenny' : 20, 'Ronin' : 35, 'Mike' : 40 }
dict2 = {'Jenny' : 25, 'Jennifer' : 21, 'Tom' : 41 }
#Update dict1 with info of dict2: Note the value of 'Jenny'
dict1.update(dict2)
print(dict1)
: {'Jenny': 25, 'Ronin': 35, 'Mike': 40, 'Jennifer': 21, 'Tom': 41}
#Update dict2 with info of dict1: Note the value of 'Jenny'
dict2.update(dict1)
print(dict1)
: {'Jenny': 20, 'Jennifer': 21, 'Tom': 41, 'Ronin': 35, 'Mike': 40}
#Value of the second dictionary (inside parenthesis) is given to 'Jenny'
#Therefore: dict1.update(dict2) != dict2.update(dict1)
--------------------------------------------------------------------------
##To convert a dictionary into a string format --> str()
dict1 = {'Jenny' : 20, 'Ronin' : 35, 'Mike' : 40}
dict1_string = str(dict1)
print(dict1_string)
: "{'Jenny' : 20, 'Ronin' : 35, 'Mike' : 40 }"
--------------------------------------------------------------------------
##To sort a dictionary --> sorted()
#The sorted() method is very flexible and allow us to sort by keys, #value, or the result of a function. The output of sorted() is a list
dict_name_age = {'Jenny' : 25, 'Jennifer' : 21, 'Tom' : 41, 'Mike' : 40}
#Sorting the dictionary by keys
sorted_dict_k = sorted(dict_name_age.items()) #Note the use of items()
print(sorted_dict_k )
: [('Jennifer', 21), ('Jenny', 25), ('Mike', 40), ('Tom', 41)]
#Sorting the dictionary by values
sorted_dict_v_r = sorted(dict_name_age.items(), key = lambda i: i[1])
print(sorted_dict_v_r)
: [('Jennifer', 21), ('Jenny', 25), ('Mike', 40), ('Tom', 41)]
#key is the variable on which we sort the dictionary by.
#i[0], i[1] refers to the keys and values of the dictionary, respectively.
#Sorting the dictionary by values in reverse order --> set reverse = True
sorted_dict_v_r = sorted(dict_name_age.items(), key = lambda i: i[1],
reverse = True)
print(sorted_dict_v_r)
: [('Tom', 41), ('Mike', 40), ('Jenny', 25), ('Jennifer', 21)]
#Sorting the dictionary by the second digit of the values
sorted_dict_v_s = sorted(dict_name_age.items(),
key = lambda i: str(i[1])[1])
print(sorted_dict_v_r)
: [('Mike', 40), ('Jennifer', 21), ('Tom', 41), ('Jenny', 25)]
#i[1] represents the values of the dictionary. To access the second digit, #first we convert the value (integer) to a string and, then we access the #second digit with indexing (index 1 in this case).
Use case
We are given a dictionary: key is the name of the customer, value is a list containing the number of coffees bought by the customer in January, February and March (in that order).
Task1 --> Sort the dictionary by number of coffees purchased in January
Task2 --> Sort the dictionary by number of coffees purchased in March
Task3a --> Create a NEW dictionary in which the value is the total number of coffees bought in the 3 months
Task3b --> Sort the new dictionary by values
coffee = { 'Mike' : [20, 5, 10], 'Gigi' : [1, 5, 10],
'Peter' : [23, 1, 33], 'Jenny' : [2, 13, 8]}
#Task1: Sort the dictionary by number of coffees purchased in January
coffee_jan = sorted(coffee.items(), key = lambda i: i[1][0])
print(coffee_jan)
: [('Gigi', [1, 5, 10]), ('Jenny', [2, 13, 8]), ('Mike', [20, 5, 10]),
('Peter', [23, 1, 33])]
#Task2: Sort the dictionary by number of coffees purchased in March
coffee_mar = sorted(coffee.items(), key = lambda i: i[1][2])
print(coffee_mar)
: [('Jenny', [2, 13, 8]), ('Mike', [20, 5, 10]), ('Gigi', [1, 5, 10]),
('Peter', [23, 1, 33])]
#Task3a: Create a NEW dictionary where values are the total number
#of coffees bought by the person (key) in the 3 months
#Approach 1 --> use of a for loop
tot_coffee = {}
for k, v in coffee.items():
tot_coffee[k] = sum(v)
print(tot_coffee)
: {'Mike': 35, 'Gigi': 16, 'Peter': 57, 'Jenny': 23}
#Approach 2 --> dictionary comprehension
tot_coffee = {k:sum(v) for k, v in coffee.items()}
print(tot_coffee)
: {'Mike': 35, 'Gigi': 16, 'Peter': 57, 'Jenny': 23}
#Task3b: Sort the new dictionary by values
tot_coffee_s = sorted(tot_coffee.items(), key = lambda i: i[1])
print(tot_coffee_s)
: [('Gigi', 16), ('Jenny', 23), ('Mike', 35), ('Peter', 57)]
Concluding remarks
Dictionaries offer a large space for sophisticated data handling in python and are a crucial tool in every complex Python script.
Comments