Python Dictionary

Python Dicitionary
••• Python Dictionary

In this article, you will learn in depth about Python dictionary from its creation to its modification, accessing its members and exploring different functional operations with built-in methods of Python.

Python Dictionary: Introduction


A Python dictionary is an ordered list of key-value pairs. The items in the dictionary are comma separated key-value pairs. Keys in Python dictionary are immutable and must be unique whereas values are mutable and can be modified or changed anytime.

Dictionary in Python is defined inside curly braces ‘{ }’. Each key is separated by a  from its value by a colon (:)  and to access and assign value, indexing operator  ‘[ ]’ is used.

If we have the key, we can retrieve its value anytime, however vice-versa doesn’t work. Hence Python dictionaries are used and optimized for retrieving data when the key is known.

How to create a Python dictionary?

As mentioned above, a Python dictionary is an ordered list of comma-separated key-value pairs, where keys and values are also separated by a colon (:).

Python dictionary can be created either by directly putting up comma-separated key-value pairs inside curly braces ‘{ }’ or by using Python built-in function get( ).

>>> #creating an empty dictionary
>>> py_dict = {}
>>> py_dict = dict()  #using built-in function dict
>>> #creating dictionary with integers as keys
>>> py_dict = {1:'a',2:'b',3:'c'}
>>> py_dict = ({1:'a',2:'b',3:'c'})  #using function dict
>>> dictionary with different data types as keys
>>> py_dict = {1:'one','a':'vowel','hi':'Danny'}

How to access values and items in a Python dictionary?

As mentioned above, keys are used to retrieve their corresponding values in Python dictionary. Keys can be used inside square brackets or we can use Python built-in function get() to access the values in the dictionary using keys.

>>> py_dict = {1:'a',2:'b',3:'c',4:'d'}
>>> #Accessing values using square brackets and keys
>>> print (py_dict[1])
a
>>> #Accessing values using get() fucntion
>>> print (py_dict.get(2))
b

what if we tried to access the item, whose key doesn’t exist in the dictionary?

>>> py_dict = {1:'a',2:'b',3:'c',4:'d'}
>>> #trying to access key that doesn't exist: eg. 5
>>> pyt_dict[5]
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
py_dict[5]
KeyError: 5
>>> #trying to access key that doesn't exist using get
>>> py_dict.get(5)
>>>

As you can see in above example, when we try to access a value whose key doesn’t exist in the dictionary using square brackets, it throws a KeyError. But when we try to access using get() function, instead of throwing KeyError, it returns nothing.

How to add keys/values to the dictionary(update dictionary)?

Since Python dictionary is mutable, we can add a new entry to the dictionary or we can also update the existing items in the dictionary.

We can add new items or update existing items by using either assignment operator or using Python built-in method update( ).

>>> py_dict = {1:'Apple',2:'Microsoft'}
>>> #Adding new items to py_dict
>>> py_dict[3]='Tesla'
>>> print (py_dict)
{1:'Apple',2:'Microsoft',3:'Tesla'}
>>> #Adding new items to py_dict using update()
>>> py_dict.update(4:'IBM')
>>> print (py_dict)
{1:'Apple',2:'Microsoft',3:'Tesla',4:'IBM'}

>>> #Updating existing values using keys and assignment operator
>>> py_dict[1]='Google'
>>> print (py_dict)
{1:'Google',2:'Microsoft',3:'Tesla',4:'IBM'}
>>> #Updating existing values using keys and update() function
>>> py_dict.update(2:'MSN')

{1:'Google',2:'MSN',3:'Tesla',4:'IBM'}

How to find the length of a Python dictionary?

Python has the built-in function len() to find the length of a dictionary.

>>> py_dict = {1:'a',2:'b',3:'c'}
>>> print (len(py_dict))
3

How to remove items from a Python dictionary?

Since dictionaries are mutable, the items in the dictionary can be removed and added. There are certain methods available in Python to delete the items or deleted entire dictionary.

  • pop(key): removes the items with provided key and returns its value to output console
  • popitem(key): same as pop(), the difference being that popitem() removes the random item and returns the (key,value) pair in the output console
  • del: deletes a single item or the dictionary entirely
  • clear(): clears all the items in the dictionary and returns an empty dictionary
>>> py_dict = {1:'a',2:'b',3:'c',4:'d',5:'e'}
>>> #Remove an item from dictionary using pop()
>>> py_dict.pop(1)
'a'
>>> print (py_dict)
{2:'b',3:'c',4:'d',5:'e'}
>>> #Remove an item using popitem()
>>> py_dict.popitem()
(5,'e')
>>> print (py_dict)
{2,'b',3:'c',4:'d'}
>>> #Remove an item using del
>>> del py_dict[2] #deletes item with key 2
>>> print (py_dict)
{3:'c',4:'d'}
>>> #Remove all item using clear()
>>> py_dict.clear()
>>> print (py_dict)  #this will return empty dictionary
{}
>>> #delete the dictionary entirely
>>> del py_dict #py_dict no longer exists and trying to access it will generate error

Iterating through a Python dictionary

We can iterate through the Python dictionary using for loop.

py_dict = {1:'a',2:'b',3:'c',4:'d'}
for x in py_dict:
  print (py_dict[x])

Output

This script will print all the values in the dictionary.

a
b
c
d

How to find maximum and minimum value in Python dictionary?

There are a couple of ways to find maximum and minimum value in a Python dictionary. Here are the examples.

>>> py_dict = {1:11,2:22,3:33}  
>>> #To find the key of max and min value
>>> key_max = max(my_dict.keys(), key=(lambda x: py_dict[x])) 
>>> print (key_max)
3 
>>> print (py_dict[key_max])  #printing maximum value
33
>>> key_min = min(py_dict.keys(), key=(lambda y: py_dict[y])) 
>>> print (key_min)
1
>>> print (py_dict[key_min])  #printing minimum value 
11
>>> #It can also be achieved like this
>>> key_max = max(py_dict, key = lambda m: py_dict[m])
>>> key_min = min(py_dict, key = lambda n: py_dict[n])
>>> print (py_dict[key_max])  #printing max value
33
>>> print (py_dict[key_min])  #printing minimum value
11

How to concatenate two Python dictionaries and create a new one?

Concatenating dictionaries in Python is not as easy as strings, tuples or lists.

There was an easier method in Python 2.7, but it no longer works in Python 3. Here are the examples.

>>> d1 = {1:2,2:3}
>>> d2 = {3:4,4:5}
>>> #This methods works on Python 2.7
>>> d3 = dict(d1.items() + d2.items())
>>> print (d3)
{1:2,2:3,3:4,4:5}
>>> #In Python 3, we can concatenate using for loop
>>> d4 = {} #declaring a empty dictionary first
>>> for x in (d1,d2): d4.update(x)
>>> print (d4)
{1:2,2:3,3:4,4:5}

Python Dictionary Methods

There are many dictionary methods in Python to play with dictionaries and use in various operations. Here is the tabulated list of Python dictionary methods.

Python dictionary methods with description
dict.clear( )
Removes all the items from the dictionary.
dict.copy( )
Return the shallow copy of a dictionary.
dict.fromkeys(seq[, value] )
Create a new dictionary with keys from seq and values set to value.
dict.get(key )
It returns corresponding value of key key . If key doesn’t exist, then it returns none.
dict.has_key(key)
Returns true if ‘key’ exist in the dictionary.
dict.items( )
Returns a new view of dictionary items.
dict.keys( )
Returns the list of keys in the dictionary.
dict.pop(key)
Removes the items with key and returns the value to console. If the key doesn’t exist in the dictionary, it raises a TypeError.
dict.popitem( )
Removes an arbitrary item in the dictionary and return it to console.
dict.setdefault(key[, v])
Returns corresponding value if the key exists already, else it inserts new key into the dictionary with the value of ‘v’ If v is empty, then value defaults to none.
dict.update(dict_x)
Updates the dictionary dict’s key/value pairs with that of from dict_x.
dict.values( )
Returns the list of values of dictinary dict.