Introduction

Dictionary data structure in Python is an unordered collection of data values, used to store data values like a map. Dictionary holds key:value pair.  Each key-value pair in a Dictionary is separated by a colon :, whereas each key is separated by a ‘comma’. Dictionaries and lists share the following characteristics:

  • Both are mutable.
  • Both are dynamic. They can grow and shrink as needed.
  • Both can be nested. A list can contain another list. A dictionary can contain another dictionary. A dictionary can also contain a list, and vice versa.

Create dictionary

Creating a dictionary is as simple as placing items inside curly braces {} separated by comma. An item has a key and the corresponding value expressed as a pair, key: value. While values can be of any data type and can repeat, keys must be of immutable type (string, number or tuple with immutable elements) and must be unique. Dictionary can also be created by the built-in function dict(). An empty dictionary can be created by just placing to curly braces{}.

# Empty dictionary
my_dict = {}

# Dictionary with integer keys
my_dict = {1: 'apple', 2: 'ball'}

# Dictionary with mixed keys
my_dict = {'name': 'John', 1: [2, 4, 3]}

# Using dict()
my_dict = dict({1:'apple', 2:'ball'})

# From sequence having each item as a pair
my_dict = dict([(1,'apple'), (2,'ball')])

# Nested Dictonary
my_dict = {1: 'H', 2: 'G', 3:{'I' : 'J', 'B' : 'K'}}

Accessing Element

Key can be used either inside square brackets or with the get() method. The difference while using get() is that it returns None instead of KeyError, if the key is not found.

my_dict = {'name':'H', 'age': 2}

# Output: H
print(my_dict['name'])

# Output: 2
print(my_dict.get('age'))

# Trying to access keys which doesn't exist throws error
# my_dict['address']

# Output: None
print(my_dict.get('address'))

Modifying Dictionary

Dictionary are mutable. We can add new items or change the value of existing items using assignment operator. If the key is already present, value gets updated, else a new key: value pair is added to the dictionary.

my_dict = {'name':'H', 'age': 2}

# Update value
my_dict['age'] = 27

# Output: {'age': 27, 'name': 'H'}
print(my_dict)

# Add item
my_dict['address'] = 'Downtown'  

# Output: {'address': 'Downtown', 'age': 27, 'name': 'H'}
print(my_dict)

# Adding Nested Key value 
my_dict[5] = {'Nested' :{'1' : 'Life'}}

Removing elements

We can remove a particular item in a dictionary by using the method pop(). This method removes as item with the provided key and returns the value. The method, popitem() can be used to remove and return an arbitrary item (key, value) form the dictionary. All the items can be removed at once using the clear() method. We can also use the del keyword to remove individual items or the entire dictionary itself.

squares = {1:1, 2:4, 3:9, 4:16, 5:25}  

# Remove a particular item
# Output: 16
print(squares.pop(4))  

# Remove an arbitrary item
# Output: (1, 1)
print(squares.popitem())

# Delete a particular item
del squares[5]  

# Remove all items
squares.clear()

# Delete the dictionary itself
del squares

Important Methods

  • clear() – Remove all items from the dictionary.
  • copy() – Return a shallow copy of the dictionary.
  • get(key[, default]) – Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.
  • items() – Return a new view of the dictionary’s items ((key, value) pairs).
  • keys() – Return a new view of the dictionary’s keys.
  • pop(key[, default]) – If key is in the dictionary, remove it and return its value, else return default. If default is not given and key is not in the dictionary, a KeyError is raised.
  • popitem() – Remove and return a (key, value) pair from the dictionary. Pairs are returned in LIFO order.
  • values() – Return a new view of the dictionary’s values.