Python dictionaries

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 a dictionary by the name 'dict' that contains employee details:

CopiedCopy Code

dict = {'Name': 'Chandra', 'Id': 200, 'Salary': 9080.50} 
							

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.

image representing python dictionary

A Python program to create a dictionary with employee details and retrieve the values upon giving the keys.

CopiedCopy Code

dict = {'Name': 'Chandra', 'Id': 200, 'Salary': 9080.50} 
print('Name of employee=', dict['Name']) 
print('Id number=', dict['Id']) 
print('Salary=', dict['Salary'])

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 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'.

If we want to know how many key-value pairs are there in a dictionary, we can use the len() function.

CopiedCopy Code

dict = {'Name': 'Chandra', 'Id': 200, 'Salary': 9080.50} 
print('Length=', len(dict))

We can modify the existing value of a key by assigning a new value, as shown in the following statement:

CopiedCopy Code

dict['Salary'] = 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:

CopiedCopy Code

dict['Dept'] = 'Finance'

This pair may be added at any place in the dictionary.

Suppose, we want to delete a key-value pair from the dictionary, we can use del statement as:

CopiedCopy Code

del dict['Id']

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

'Gender' not in dict

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 same key again, the old key will be overwritten and only the new key will be available. Consider the following example:

CopiedCopy Code

emp = {'Nag':10, 'Vishnu':20, 'Nag':30}
print(emp)

Keys should be immutable type. For example, we can use a number, string 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'.

CopiedCopy Code

emp = {['Nag']:10, 'Vishnu':20, 'Raj':30} 
							

Output:

TypeError: unhashable type: 'list'

Dictionary Methods

Various methods are provided to process the elements of a dictionary. These methods generally retrieve or manipulate the contents of a dictionary.

table of python dictionary methods

A Python program to retrieve keys, values and key-value pairs from a dictionary.

CopiedCopy Code

dict = {'Name': 'Chandra', 'Id': 200, 'Salary': 9080.50} 
print(dict) 
print('Keys in dict=', dict.keys()) 
print('Values in dict=', dict.values()) 
print('Items in dict=', dict.items())


A Python program to create a dictionary and find the sum of values.

CopiedCopy Code

dict = eval(input("Enter elements in {}:")) 
#find the sum of values 
s = sum(dict.values()) 
print('Sum of values in the dictionary:', s)


First we 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:

CopiedCopy Code

x.update({k:v})

 
							

A Python program to create a dictionary from keyboard and display the elements.

CopiedCopy Code

x = {} 
n = int(input('How many elements?')) 
for i in range(n): 
   k = input('Enter key:')   #key is string 
   v = int(input('Enter its value:')) #value is integer 
   x.update({k:v})
print('The dictionary is:', x)


A Python program to create a dictionary with cricket players names and scores in a match. Also we are retrieving runs by entering the player's name.

CopiedCopy Code

x = {} 
n = int(input('How many players?')) 
for i in range(n): 
   k = input('Enter player name:') 
   v = int(input('Enter runs:')) 
   x.update({k:v}) 
print('\nPlayers in this match:') 
for pname in x.keys(): #keys() will give only keys 
   print(pname) 
name = input('Enter player name:') 
runs = x.get(name, -1) 
if(runs == -1): 
   print('Player not found') 
else: 
   print('{} made runs {}.'.format(name, runs))

Using for Loop with Dictionaries

For loop is very convenient to retrieve the elements of a dictionary. Let's take a simple dictionary that contains color code and its name as:

CopiedCopy Code

colors = {'r': "Red", 'g': "Green", 'b': "Blue", 'w': "White"}
for k in colors: 
   print (k)

for k in colors: 
   print (colors[k])

for k, v in colors.items(): 
   print('Key= {} Value= {}'. format(k, v))

Sort elements of dictionary

A lambda is a function that does not have a name. Lambda functions are written using a single statement and hence look like expressions. Lambda functions are written without using 'def' keyword. They are useful to perform some calculations or processing easily.

CopiedCopy Code

f = lambda x, y: x+y
colors = {10: "Red", 35: "Green", 15: "Blue", 25: "White"}

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:

sorted(elements, key = color code

Here, elements of the dictionary can be accessed using the colors.items() method. A key can be prescribed using a lambda function as:

CopiedCopy Code

key = lambda t: t[0]

The sorted() function can be written as:

CopiedCopy Code

sorted(colors.items(), key = lambda t: t[0])

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:

CopiedCopy Code

sorted(colors.items(), key = lambda t: t[1]) 
							

This will sort the elements of the dictionary by taking color name (indicated by t[1]) as the key.

A Python program to sort the elements of a dictionary based on a key or value.

CopiedCopy Code

colors = {10: "Red", 35: "Green", 15: "Blue", 25: "White"}
c1 = sorted(colors.items(), key = lambda t: t[0]) 
print(c1) 
c1 = sorted(colors.items(), key = lambda t: t[0],reverse=True)
print(c1)
c2 = sorted(colors.items(), key = lambda t: t[1]) 
print(c2)
c2 = sorted(colors.items(), key = lambda t: t[1],reverse=True) 
print(c2)

Lists into Dictionary

When we have two lists, it is possible to convert them into a dictionary. For example, we have two lists containing names of countries and names of their capital cities.

CopiedCopy Code

countries = ["USA", "India", "Germany", "France"] 
cities = ['Washington', 'New Delhi', 'Berlin', 'Paris'] 

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.

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:

CopiedCopy Code

z = zip(countries, cities) 
							

The zip() function is useful to convert the sequences into a zip class object.

The second step is to convert the zip object into a dictionary by using dict() function.

CopiedCopy Code

d = dict(z) 
							

A Python program to convert the elements of two lists into key-value pairs of a dictionary.

CopiedCopy Code

countries = ["USA", "India", "Germany", "France"] 
cities = ['Washington', 'New Delhi', 'Berlin', 'Paris'] 

z = zip(countries, cities) 
d = dict(z) 
print('{:15s} -- {:15s}'.format('COUNTRY', 'CAPITAL')) 
for k in d: 
   print('{:15s} -- {:15s}'.format(k, d[k]))

Strings into Dictionary

When a string is given with key and value pairs separated by some delimiter (or separator) like a comma (,) we can convert the string into a dictionary and use it as dictionary.

CopiedCopy Code

str = "Sujay=23, Rajesh=20, Lahari=19,Nithin=22"
							

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 brake the string at equals (=) symbol. This can be done using a for loop as:

CopiedCopy Code

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:

CopiedCopy Code

lst.append(y)

The third step is to convert the list into a dictionary 'd' using dict() function as:

CopiedCopy Code

d = dict(lst)

A Python program to convert a string into key-value pairs and store them into a dictionary.

CopiedCopy Code

str = "Vijay=23,Ganesh=20,Lakshmi=19,Nikhil=22" 
lst=[] 
for x in str.split(','): 
   y= x.split('=') 
   lst.append(y) 

d = dict(lst) 
d1={} 
for k, v in d.items(): 
   d1[k] = int(v) 
print(d1)

Pass Dictionaries to functions

We can pass a dictionary to a function by passing the name of the dictionary. Let's define a function that accepts a dictionary as a parameter.

CopiedCopy Code

def fun(dictionary): 
   for i, j in dictionary.items(): 
print(i, '--', j)

A Python function to accept a dictionary and display its elements.

CopiedCopy Code

def fun(dictionary): 
   for i, j in dictionary.items(): 
      print(i, '--', j)

d = {'a':'Apple', 'b': 'Book', 'c': 'Cook'} 
fun(d)

Ordered Dictionaries

We had already discussed that the elements of a dictionary are not ordered. It means the elements are not stored into the same order as they were entered into the dictionary. Sometimes this becomes a problem.

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 OrderedDict() method of 'collections' module.

So, first we should import this method from collections module, as: from collections import OrderedDict

Once this is done, we can create an ordered dictionary with the name 'd' as:

d = OrderedDict()

A Python program to create a dictionary that does not change the order of elements.

CopiedCopy Code

from collections import OrderedDict 
d = OrderedDict()
d[10] = 'A' 
d[11] = 'B' 
d[12] = 'C' 
d[13] = 'D' 
for i, j in d.items(): 
   print(i, j)