Dictionaries in Python
Dictionaries in Python
A dictionary represents a group of elements arranged in the form of key-value pairs. In the
dictionary, the first element is considered as 'key' and the immediate next element is taken as its
'value'. The key and its value are separated by a colon (). All the key-value pairs in a dictionary
are inserted in curly braces{ }. Let's take dictionary by the name 'dict' that contains employee
details:
Here, the name of the dictionary is 'dict'. The first element in the dictionary is a string ‘Name'.
So, this is called 'key'. The second element is 'Chandra' which is taken as its value. Observe
that the key and its value are separated by a colon. Similarly, the next element is 'Id' which
becomes 'key' and the next element ‘200’ becomes its value. Finally, Salary becomes key and
‘9080.50' becomes its value. So, we have 3 pairs of keys and values in this dictionary.
When the ‘key’ is provided, we can get back its ‘value’. This is how we search for the values in a
dictionary. For example, 'Name' is the key. To get its value, i.e. ‘Chandra', we should mention the
key as an index to the dictionary, as: dict['Name’]. This will return the value ‘Chandra'. Similarly,
dict['Id'] returns its value, i.e. 200.
Ex:
Output:
Operations on Dictionaries
To access the elements of a dictionary, we should not use indexing or slicing. For example,
dict[0] or dict[1:3] etc expressions will give an error. To access the value associated with a key,
we can mention the key name inside the square braces, as: dict[Name]. This will return the
value associated with Name. This is nothing but ‘Chandra’.
Learnvista Pvt Ltd.
2nd Floor, 147, 5th Main Rd, Rajiv Gandhi Nagar HSR Sector 7,Near Salarpuria Serenity, Bengaluru, Karnataka 560102
Mob:- +91 779568798, Email:- [email protected]
If we want to know how many key-value pairs are there in a dictionary, we can use the len)
function, as shown in the following statements:
dict={ ‘Name': 'Chandra', 'Id': 200, "salary: 9080.50}
n=len(dict)
print('No. of key-value pairs=’, n)
Please remember each key-value pair is counted as one element. We can modify the existing
value of a key by assigning a new value, as shown in following statement:
dict['salary'] = 10500.00
Here, the 'Salary' value is modified as ‘10500.00’. The previous value of "Salary”,i.e. 9080.50 is
replaced by the new value, i.e. 10500.00.
We can also insert a new key-value pair into an existing dictionary. This is done by mentioning
the key and assigning a value to it, as shown in the following statement:
dict["Dept'] = 'Finance’
Here, we are giving a new key ‘Dept’ and its value ‘Finance’. This pair is stored into the
dictionary ‘dict’. Now, if we display the dictionary using print(dict), it will display:
Observe the new pair 'Dept’: ‘Finance' is added to the dictionary. Also, observe that this pair is
not added at the end of existing pairs. It may be added anywhere in the dictionary.
Suppose, we want to delete a key-value pair from the dictionary, we can use del statement as:
del dict['Id']
This will delete the key 'Id' and its corresponding value from the dictionary. Now, the dictionary
looks like this:
{"Name":"Chandra", "Dept": "Finance”. "salary”: 10500.03}
To test whether a ‘key' is available in a dictionary or not, we can use ‘in' and 'not in’ operators.
These operators return either True or False Consider the following statement:
'Dept’ in dict
Learnvista Pvt Ltd.
2nd Floor, 147, 5th Main Rd, Rajiv Gandhi Nagar HSR Sector 7,Near Salarpuria Serenity, Bengaluru, Karnataka 560102
Mob:- +91 779568798, Email:- [email protected]
The preceding statement will give
True
False
True
We can use any datatypes for values. For example, a value can be a number, string, list,tuple or
another dictionary. But keys should obey the following rules:
● Keys should be unique. It means, duplicate keys are not allowed. If we enter the same
key again, the old key will be overwritten and only the new key will be available.
Consider the following example:
emp={‘Nag’:10, ‘vishnu':20, ‘Nag’:30}
print(emp).
● Keys should be an immutable type. For example, we can use numbers, strings or tuples
as keys since they are immutable. We cannot use lists or dictionaries as keys. If they are
used as keys, we will get TypeError. Consider the following example:
copy() d1=d.copy() Copies all elements from ‘d' into a new dictionary ‘d1’.
fromkeys() d.fromkeys(s[,v]) Create a new dictionary with keys from sequence ‘s’ and
values all set to ‘v’
get() d.get(k [,v]) Returns the value associated with key k. If the key is not
found, it returns ‘v’.
pop() d.pop(k [v]) Removes the key k' and its value from 'd' and returns the
value. If the key is not found, then the value ‘v’ is returned.
If key is not found and 'v' is not mentioned then KeyError' is
raised.
setdefault() d.setdefault(k [v]) then KeyError' is raised.If key k' is found, its value is
returned. If key is not found, then the k, v pair is stored into
the dictionary ‘d’
In the program below, we are going to retrieve keys from a dictionary using the keys() method
The keys() method returns a dict_keys object that contains only keys. We will also retrieve
values from the dictionary using the values() method. This method returns all values in the form
of dict_values object. Similarly, the items() method can be used to retrieve all key value pairs
into dict_items objects.
Ex:
.
In the program below, we are going to create a dictionary by entering the elements from the
keyboard. When we enter the elements from the keyboard inside curly braces, then they are
treated as key-value pairs of a dictionary by the eval() function. Once the elements are entered,
we want to find the sum of the values using the sum() function on the values of the dictionary.
Ex:
Output:
In the program below, we first create an empty dictionary ‘x'. We enter the key into ‘k' and value
into ‘v’ and then using the update() method, we will store these key-value pairs into the
dictionary ‘x’, as shown in the following statement:
x.update({k:v})
Here, the update() method stores the ‘k' and ‘v' pair into the dictionary ‘x’.
Prograin
Program 4: A Python program to create a dictionary from keyboard and display the elements.
Please observe the output of the above program. The key-value pairs which are entered by us
from the keyboard are not displayed in the same order. Dictionaries will not maintain orderliness
of pairs.
In the following program, we are creating a dictionary with cricket players' names and scores.
That means, the player name becomes key and the score becomes its value. Once the
dictionary ‘x’ is created, we can display the players' names by displaying the keys as:
In the get() method, we should provide the key, i.e. player name. If the key is found in the
dictionary, this method returns his runs'. If the player is not found in the dictionary, then it returns
-1.
for k in colors:
print (k)
In the above loop, ‘k' stores each element of the colors dictionary. Here, 'k’ assumes only keys
and hence this loop displays only keys. Suppose, we want to retrieve values, then we can
obtain them by passing the key to the colors dictionary, as: color[k]. The following for loop
retrieves all the values from the colors dictionary:
for k in colors:
print (colors[k])
Since values are associated with keys, we can retrieve them only when we mention the keyn.
Suppose, we want to retrieve both the keys and values, method in for loop as:
In the preceding code, the colors.items() method returns an object by the name 'dict_items’ that
contains key and value pairs. Each of these pairs is stored into ‘k', ‘v’ and then displayed.
Output:
dict.get(x, 0)
This statement says that if the key 'x' is found in the dictionary 'dict', then return its ‘value' from
the dictionary, else return 0. Now, consider the following code:
dict={}
str=”Book”
for x in str:
dict[x] = dict.get(x,0)+1
Let's take the first letter of the string, i.e. 'B'. Since the dictionary is initially empty, there are no
elements in it and hence 'B' is not found in the dictionary. So, dict.get(x, 0)+1 returns 1. On the
left side, we have dict(x). It represents dict['B’]. Here, 'B' is taken as key. So, the statement
becomes:
dict [‘B’]=1
It means B' is stored as a key and 1 is stored as its value into the dictionary 'dict'. So the
dictionary contains a pair of elements as: {‘B’:1}.In the next step, 'o' is the letter for which the
get() method searches in the dictionary. It is not found in the 'dict' and hence 1 is returned. So,
dict['o']=1
This will store the new key-value pair, i.e. 'o' and 1 into the dict' and hence the dictionary
contains:
In the next repetition of the for loop, we get 'o' into x. Since it is already available in the dict', its
value 1 is returned by the get() method for which I will be added. So, we get: dict['0'] = 2 It
means, the old value of 'o' is now updated to 2 in the dictionary and 'dict' contains the elements:
{‘B’: 1, ‘o’: 2}. In this way, 'dict' stores each letter as a key and its number of occurrences as
value.
B No 1 dict[‘B’]=1 {‘B’:1}
o No 1 dict[‘o’]=2 {‘B’:1,‘o’:1}
k No 1 dict[‘k’]=1 {‘B’:1,‘o’:1,’k’:1}
The output of the above program may not show the letter occurrences in an orderly manner.
This is because the dictionary does not store the elements in the same order as they were
entered.
f=lambda x, y: x+y
The above expression is a lambda function with 2 arguments, x and y. After colon (:), we wrote
the body, L.e. x+y. This is the value returned by the lambda function. At the time of calling this
function, we are supposed to pass 2 values for x and y as: f(10, 15). This will return 25 as result.
Here, color code and its name are given as key-value pairs. Suppose we want to sort this
dictionary into ascending order of keys, i.e on color codes, we can use sorted() function in the
following format:
Here, elements of the dictionary can be accessed using the colors.items() method. A key can be
prescribed using a lambda function as:
Learnvista Pvt Ltd.
2nd Floor, 147, 5th Main Rd, Rajiv Gandhi Nagar HSR Sector 7,Near Salarpuria Serenity, Bengaluru, Karnataka 560102
Mob:- +91 779568798, Email:- [email protected]
key=lambda t: t[0]
Here, ‘t' is the argument for the lambda function and t[0] is the value returned by the function.
Since we are supposed to sort the dictionary, we should pass the entire dictionary to the lambda
function. So, ‘t’ represents the dictionary that is passed to the function and t[0] represents the
0th element in the dictionary, i.e. color code. So, the sorted() function can be written as:
This will sort all the elements of the dictionary by taking color code (indicated by t[0]) as the key.
If we want to sort the dictionary based on color name, then we can write:
This will sort the elements of the dictionary by taking the color name (indicated by t[1]) as the
key.
Output:
We want to create a dictionary out of these two lists by taking the elements of countries list as
keys and of 'cities' list as values. The dictionary should look something like this:
There are two steps involved to convert the lists into a dictionary. The first step is to create a
‘zip' class object by passing the two lists to zip() function as:
z = zip(countries, cities)
The zip() function is useful to convert the sequences into a zip class object. There may be 1 or
more sequences that can be passed to the zip() function. Of course, we passed only 2 lists to
the zip() function in the above statement. The resultant zip object is ‘z’.
The second step is to convert the zip object into a dictionary by using dict() function.
d = dict(z)
Here, the 0th element of z is taken as key and the 1st element is converted into its value.
Similarly, the 2nd element becomes ‘key' and 3rd one becomes its ‘value', etc. They are stored
into the dictionary ‘d’. If we display 'd', we can see the following dictionary:
Output:
This string 'str' contains names and their ages. Each pair is separated by a comma (,). Also
each name and age are separated by equal (=) symbol. To convert such a string into a
dictionary, we have to follow 3 steps. First, we should split the string into pieces where a comma
is found using split() method and then break the string at equals ( = )symbol. This can be done
using a for loop as:
for x in str.split('.'):
y x.split(‘=’)
Each piece of the string is available in ‘y'. The second step is to store these pieces into a list ‘lst’
using append() method as:
lst.append()
The third step is to convert the list into a dictionary 'd' using dict() function as:
d = dict(lst)
Please observe that this dictionary contains all elements as strings only. See first pair:
‘vijay’:’ 23’. Here, ‘Vijay' is a string and his age '23' is also stored as a string. If we want we can
convert this ‘23' into an integer using the int() function. Then we can store the name and age
into another dictionary 'd1' as:
for k, v in d. items():
d1[k] = int(v)
Here, k represents the key and int(v) represents the converted value being stored into d1.
This function fun() is taking a 'dictionary' object as a parameter. Using a for loop, we are
displaying the key-value pairs of the dictionary. To call this function and pass a dictionary 'd', we
can simply write:
fun (d)
Output:
An ordered dictionary is a dictionary but it will keep the order of the elements. The elements are
stored and maintained in the same order as they were entered into the ordered dictionary. We
can create an ordered dictionary using the Ordered Dict() method of collections' module. So,
first we should import this method from collections module, as:
d[10] = 'A'
d[11] = 'B'
d[12] =’C’
d[13] =’D’
Here, 10 is the key and 'A' is its value and so on. This order is not disturbed as 'd' is an ordered
dictionary. When we display the key-value pairs from the dictionary 'd', we can see the same
order.