Python Data Type Dictionary

In this section, you will learn dictionary in Python. You will learn how to create a dictionary and how to add and delete elements from a dictionary.

Dictionary is a Python native data type whose data/values are key-value pairs. A dictionary contains unordered elements. A piece of data or value of the dictionary can be retrieved if you know the key.

Create a dictionary:

A dictionary can be created using curly braces {} with each element to be a pair containing key and value.

Python dictionary keys must be of immutable data type, and values can be of any type.

Consider the example below:

>>> x = {1:'blue', 'key':'pink'}
>>> print(type(x))
<class 'dict'>
>>> print('x[1] = ', x[1])      #using key to retrive value
x[1] =  blue
>>> print("x['key'] =", x['key']) #using key to retrive value
x['key'] = pink

A dictionary can also be initialized using the dict() method.

>>> dict({1: 'Blue', 2: 'Pink'})
{1: 'Blue', 2: 'Pink'}

get() Method to Access Elements of Dictionary:

You can access the values of a dictionary by using keys. Keys can be used either with the index access operator as done above or with the get() method.

If the key is not found when using get() method, None will be returned instead of an error.

>>> d = dict({1: 'Blue', 2: 'Pink'})
>>> print(d[1])
>>> print(d.get(1))
>>> print(d[3])
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
KeyError: 3
>>> print(d.get(3))

Update Elements of Dictionary:

Dictionary is mutable, so you can update, add and delete elements from a dictionary. The elements of a dictionary can be updated by using assignment operator.

When updating elements with a key that does not exist in the dictionary, a new key-value pair will be created, otherwise, the corresponding value will be updated.

>>> d = dict({1: 'Blue', 2: 'Pink'})
>>> d[1] = 'Yellow'
>>> print(d)
{1: 'Yellow', 2: 'Pink'}
>>> d[3] = 'Black'
>>> print(d)
{1: 'Yellow', 2: 'Pink', 3: 'Black'}

Delete Elements From Dictionary:

The following are some ways to delete elements from dictionary:

  1. pop() method: It will remove and return the value of corresponding given key.
  2. popitem() method: It will remove and return an arbitrary (key, value) from the dictionary.
  3. clear() method: It will delete all the elements from the dictionary but not the dictionary.
  4. del keyword: It can remove a particular method or the entire dictionary.

Consider the example below:

>>> d = dict({1: 'Blue', 2: 'Pink', 3:'Yellow', 4:'Red'})
>>> print(d.pop(2))
>>> print(d)
{1: 'Blue', 3: 'Yellow', 4: 'Red'}
>>> print(d.popitem())
(4, 'Red')
>>> print(d)
{1: 'Blue', 3: 'Yellow'}
>>> del d[3]
>>> print(d)
{1: 'Blue'}
>>> d.clear()
>>> print(d)
>>> del d
>>> print(d)
Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
NameError: name 'd' is not defined

Methods Applicable to Python Dictionary:

Consider the table below:

Method Description
clear() clear all the items from the dictionary
copy() copy a dictionary
fromkeys(seq[,v]) return a dictionary with seq elements as keys and values will be equal to v
get(key[,d]) get the value of the key and if there is no key, d will be returned.
items() return the items of the dictionary as (key, value)
keys() return the keys of a dictionary
pop(key[,d]) remove an item corresponding to the key. If the key doesn’t exist value corresponding to d will be returned. If both d and key do not exist an error will be raised.
popitem() It will return and remove both key and value from the dictionary.
setdefault(key[,d]) return the value of the key. If the key is not found, a new key will be created with value d and d will be returned.
update([other]) update the dictionary with keys and values as other.
values() return the values of a dictionary

Other Dictionary Operations:

Dictionary Membership Check:

The in keyword checks if an item is a member of the dictionary or not.

The keys of a dictionary are used in membership check but not the values.
>>> d = dict({1: 'Blue', 2: 'Pink', 3:'Yellow', 4:'Red'})
>>> print(2 in d)
>>> print(5 in d)

Iterate Through a Dictionary:

You can iterate through a dictionary by using for loop:

>>> d = dict({1: 'Blue', 2: 'Pink', 3:'Yellow', 4:'Red'})
>>> for i in d:

Built-in Functions with Dictionary:

The following are some of the built-in functions that can be used with dictionaries to perform different tasks:

Functions Description
all() return True when all the keys of the dictionary are True. It also returns True when the dictionary is empty.
any() return True when any of the key of the dictionary is True. It returns False when the dictionary is empty.
cmp() compare two dictionaries
len() return the number of items in a dictionary or the length of the dictionary.
sorted() return a sorted list of keys of a dictionary.

Consider the following code:

>>> d = dict({1: 'Blue', 2: 'Pink', 3:'Yellow', 4:'Red'})
>>> print(len(d))
>>> print(sorted(d))
[1, 2, 3, 4]