Python Dictionary

What is Python dictionary?

Dictionaries are Python’s implementation of a data structure, generally known as associative arrays, hashes, or hashmaps.

You can think of a dictionary as a set of key:value pairs; where each key is mapped to a single value.

The important properties of Python dictionaries are as follows:

  • Dictionaries are unordered – Items stored in a dictionary aren’t kept in any particular order.
  • Dictionaries are changeable (mutable) – They can be changed in place, can grow and shrink on demand.
  • Accessed by keys – Dictionary items are accessed by keys, not by their position (index).
  • Dictionaries can be nested – A dictionary can contain another dictionary (Nested Dictionary).

Create a Dictionary

You can create a dictionary by placing a comma-separated list of key:value pairs in curly braces {}.

Each key is separated from its associated value by a colon :

Example: Create a dictionary to store employee record

D = {'name': 'Bob',
     'age': 25,
     'job': 'Dev',
     'city': 'New York',
     'email': 'bob@web.com'}
dictionary key value pairs illustration2

Dictionaries are pretty straightforward, but here are a few points you should be aware of when using them.

Keys must be unique:

A key can appear in a dictionary only once.

Even if you specify a key more than once during the creation of a dictionary, the last value for that key becomes the associated value.

Example:

D = {'name': 'Bob',
     'age': 25,
     'name': 'Jane'}
print(D)    # {'name': 'Jane', 'age': 25}

Notice that the first occurrence of ‘name’ is replaced by the second one.

Key must be immutable type:

You can use any object of immutable type as dictionary keys – such as numbers, strings, booleans or tuples.

Example:

D = {(2,2): 25,
     True: 'a',
     'name': 'Bob'}

An exception is raised when mutable object is used as a key.

Example:

# TypeError: unhashable type: 'list'
D = {[2,2]: 25,
     'name': 'Bob'}

Value can be of any type:

There are no restrictions on dictionary values. A dictionary value can be any type of object and can appear in a dictionary multiple times.

Example:

# values of different datatypes
D = {'a':[1,2,3],
     'b':{1,2,3}}
# duplicate values
D = {'a':[1,2],
     'b':[1,2],
     'c':[1,2]}

The dict() Constructor

You can convert two-value sequences into a dictionary with Python’s dict() constructor.

The first item in each sequence is used as the key and the second as the value.

Example: Create a dictionary with a list of two-item tuples

L = [('name', 'Bob'),
     ('age', 25),
     ('job', 'Dev')]

D = dict(L)
print(D)    # {'name': 'Bob', 'age': 25, 'job': 'Dev'}

Example: Create a dictionary with a tuple of two-item lists

T = (['name', 'Bob'],
     ['age', 25],
     ['job', 'Dev'])

D = dict(T)
print(D)    # {'name': 'Bob', 'age': 25, 'job': 'Dev'}

When the keys are simple strings, it is sometimes easier to specify key:value pairs using keyword arguments.

Example: Specifying key:value pairs using keyword arguments

D = dict(name = 'Bob',
         age = 25,
         job = 'Dev')

print(D)    # {'name': 'Bob', 'age': 25, 'job': 'Dev'}

Other Ways to Create Dictionaries

There are lots of other ways to create a dictionary.

You can use dict() function along with the zip() function, to combine separate lists of keys and values obtained dynamically at runtime.

Example: Create a dictionary with list of zipped keys/values

keys = ['name', 'age', 'job']
values = ['Bob', 25, 'Dev']

D = dict(zip(keys, values))

print(D)    # {'name': 'Bob', 'age': 25, 'job': 'Dev'}

You’ll often want to create a dictionary with default values for each key. The fromkeys() method offers a way to do this.

Example: Initialize dictionary with default value ‘0’ for each key

keys = ['a', 'b', 'c']
defaultValue = 0

D = dict.fromkeys(keys,defaultValue)

print(D)    # {'a': 0, 'b': 0, 'c': 0}

There is one more way to create a dictionary based on existing dictionary, called Dictionary comprehension.

Access Dictionary Items

You can fetch a value from a dictionary by referring to its key in square brackets [].

Example: Print the value of the key ‘name’

D = {'name': 'Bob',
     'age': 25,
     'job': 'Dev'}

print(D['name'])    # Bob

If you refer to a key that is not in the dictionary, you’ll get an exception.

Example: Try to print the value of the key ‘job’

print(D['salary'])    # KeyError: 'salary'

To avoid such exception, you can use the special dictionary get() method.

This method returns the value for key if key is in the dictionary, else None, so that this method never raises a KeyError.

Example: Print values of the keys ‘name’ and ‘salary’

# key present
print(D.get('name'))      # Bob
# key absent
print(D.get('salary'))    # None

Add or Update Dictionary Items

Adding or updating dictionary items is easy. Just refer to the item by its key and assign a value.

If the key is already present in the dictionary, its value is replaced by the new one.

Example: Change the value of the key ‘name’

D = {'name': 'Bob',
     'age': 25,
     'job': 'Dev'}

D['name'] = 'Sam'
print(D)    # {'name': 'Sam', 'age': 25, 'job': 'Dev'}

If the key is new, it is added to the dictionary with its value.

Example: Add new item ‘city’ to the dictionary

D = {'name': 'Bob',
     'age': 25,
     'job': 'Dev'}

D['city'] = 'New York'
print(D)
# {'name': 'Bob', 'age': 25, 'job': 'Dev', 'city': 'New York'}

Merge Two Dictionaries

Use the built-in update() method to merge the keys and values of one dictionary into another.

Note that this method blindly overwrites values of the same key if there’s a clash.

Example: Merge dictionary ‘D2’ into ‘D1’

D1 = {'name': 'Bob',
      'age': 25,
      'job': 'Dev'}

D2 = {'age': 30,
      'city': 'New York',
      'email': 'bob@web.com'}

D1.update(D2)
print(D1)
# {'name': 'Bob', 'age': 30, 'job': 'Dev',
#  'city': 'New York', 'email': 'bob@web.com'}

Remove Dictionary Items

There are several ways to remove items from a dictionary.

Remove an Item by Key

If you know the key of the item you want, you can use pop() method. It removes the key and returns its value.

Example: Remove key ‘age’ and return its value

D = {'name': 'Bob',
     'age': 25,
     'job': 'Dev'}

x = D.pop('age')
print(D)    # {'name': 'Bob', 'job': 'Dev'}

# removed value
print(x)    # 25

If you don’t need the removed value, use the del statement.

Example: Remove ‘age’ from the dictionary

D = {'name': 'Bob',
     'age': 25,
     'job': 'Dev'}

del D['age']
print(D)    # {'name': 'Bob', 'job': 'Dev'}

Remove Last Inserted Item

The popitem() method removes and returns the last inserted item.

Example: Remove last inserted item from the dictionary

D = {'name': 'Bob',
     'age': 25,
     'job': 'Dev'}

x = D.popitem()
print(D)    # {'name': 'Bob', 'age': 25}

# removed pair
print(x)    # ('job', 'Dev')

In versions before 3.7, popitem() would remove a random item.

Remove all Items

To delete all keys and values from a dictionary, use clear() method.

Example: Empty entire dictionary

D = {'name': 'Bob',
     'age': 25,
     'job': 'Dev'}

D.clear()
print(D)    # {}

Get All Keys, Values and Key:Value Pairs

There are three dictionary methods that return all of the dictionary’s keys, values and key-value pairs: keys(), values(), and items().

These methods are useful in loops that need to step through dictionary entries one by one.

All the three methods return iterable object. If you want a true list from these methods, wrap them in a list() function.

Example:

D = {'name': 'Bob',
     'age': 25,
     'job': 'Dev'}

# get all keys
print(list(D.keys()))    # ['name', 'age', 'job']

# get all values
print(list(D.values()))  # ['Bob', 25, 'Dev']

# get all pairs
print(list(D.items()))   # [('name', 'Bob'), ('age', 25), ('job', 'Dev')]

Iterate Through a Dictionary

If you use a dictionary in a for loop, it traverses the keys of the dictionary by default.

Example:

D = {'name': 'Bob',
     'age': 25,
     'job': 'Dev'}

for x in D:
    print(x)    # name age job

To iterate over the values of a dictionary, index from key to value inside the for loop.

Example:

D = {'name': 'Bob',
     'age': 25,
     'job': 'Dev'}

for x in D:
    print(D[x])    # Bob 25 Dev

Check if a Key or Value Exists

If you want to know whether a key exists in a dictionary, use in and not in operators with if statement.

Example: Check if a key exists in a dictionary

D = {'name': 'Bob',
     'age': 25,
     'job': 'Dev'}

print('name' in D)      # True
print('salary' in D)    # False

To check if a certain value exists in a dictionary, you can use values() method.

Example: Check if a value exists in a dictionary

D = {'name': 'Bob',
     'age': 25,
     'job': 'Dev'}

print('Bob' in D.values())    # True
print('Sam' in D.values())    # False

Find Dictionary Length

To find how many key:value pairs a dictionary has, use len() method.

Example: Find length of a dictionary

D = {'name': 'Bob',
     'age': 25,
     'job': 'Dev'}

print(len(D))    # 3

Python Dictionary Methods

Python has a set of built-in methods that you can invoke on dictionary objects.

Python Dictionary Methods
MethodDescription
clear()Removes all items from the dictionary
copy()Returns a shallow copy of the dictionary
fromkeys()Creates a new dictionary with the specified keys and values
get()Returns the value of the specified key
items()Returns a list of key:value pair
keys()Returns a list of all keys from dictionary
pop()Removes and returns single dictionary item with specified key.
popitem()Removes and returns last inserted key:value pair from the dictionary.
setdefault()Returns the value of the specified key, if present. Else, inserts the key with a specified value.
update()Updates the dictionary with the specified key:value pairs
values()Returns a list of all values from dictionary

Built-in Functions with Dictionary

Python also has a set of built-in functions that you can use with dictionary objects.

Python Built-in Functions with Dictionary
MethodDescription
all()Returns True if all list items are true
any()Returns True if any list item is true
len()Returns the number of items in the list
sorted()Returns a sorted list