Python Dictionaries – A collection of key-value pairs

After strings and lists, let’s talk about dictionaries.

Like a real-life dictionary has words and meanings, Python dictionaries have keys and values. They are an important data structure in Python and today, we will learn how to create, access, manipulate and use them.

What are Dictionaries in Python?

Dictionaries in Python are collections that are unordered, indexed and mutable. They hold keys and values. This is a dictionary:

Code:

>>> animals={'dog': 'mammal', 'cat': 'mammal', 'snake': 'reptile', 'frog': 'amphibian'}

Dictionaries are in curly brackets.

Key-value pairs are separated by commas and keys and values are separated by colons. Keys in dictionaries are unique and immutable.

Unlike other data structures, dictionaries hold two items in pairs instead of a single item. This is like a real-life dictionary. You can search for a value if you know the key. One key cannot have two values.

Code:

>>> dict1={1:4, 1:9, 2:7}
>>> dict1

Output:

{1: 9, 2: 7}

The value of 1 is 9, not 4.

Creating Dictionaries in Python

There are many ways to create a dictionary.

Code:

>>> squares={1:1, 2:4, 3:9}

>>> squares={}
>>> squares[1]=1
>>> squares[2]=4
>>> squares[3]=9
>>> squares

Output:

{1: 1, 2: 4, 3: 9}

Code:

>>> squares=dict()
>>> squares[1]=1
>>> squares[2]=4
>>> squares[3]=9
>>> squares

Output:

{1: 1, 2: 4, 3: 9}

Code:

>>> squares={num:num**2 for num in range(1,4)}
>>> squares

Output:

{1: 1, 2: 4, 3: 9}

Accessing Items in Python Dictionaries

After you have defined a dictionary, how do you access its items? There are two ways to do this- indexing and the get() method.

1. Indexing

Dictionaries are unordered but we can index them with their keys.

Let’s take an example.

Code:

>>> squares

Output:

{1: 1, 2: 4, 3: 9}

Code:

>>> squares[2]

Output:

4

Code:

>>> squares={'one':1, 'two':4, 'three':9}
>>> squares['two']

Output:

4

2. get()

The get() method does the same thing as indexing. It takes a parameter for the key for which we want to find the value.

Code:

>>> squares.get('one')

Output:

1

If the key does not exist in the dictionary, it returns None.

Code:

>>> squares.get('four')
>>>

Adding Items in Python Dictionaries

If you have a dictionary (empty or non-empty) and want to add more key-value pairs to it, you can:

Code:

>>> squares

Output:

{‘one’: 1, ‘two’: 4, ‘three’: 9}

Code:

>>> squares['four']=16
>>> squares['five']=25
>>> squares['six']=36

squares is this dictionary now:

Code:

>>> squares

Output:

{‘one’: 1, ‘two’: 4, ‘three’: 9, ‘four’: 16, ‘five’: 25, ‘six’: 36}

Removing Items in Python Dictionaries

Dictionaries are mutable and so we can remove items from them.

Let’s look at different ways to do this:

1. pop()

The pop() method removes the item with the key we specify.

Code:

>>> squares={1:1, 2:4, 3:9, 4:16, 5:25, 6:36, 7:49, 8:64, 9:81, 10:100}
>>> squares.pop(7)

Output:

49

If the key is not present in the dictionary, it raises a KeyError.

Code:

>>> squares.pop(11)

Output:

Traceback (most recent call last):
  File “<pyshell#32>”, line 1, in <module>
    squares.pop(11)
KeyError: 11

2. popitem()

This method removes the last inserted item from the dictionary and returns it.

Code:

>>> squares.popitem()

Output:

(10, 100)

Code:

>>> squares

Output:

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 8: 64, 9: 81}

3. del

We can use the del keyword to delete dictionary items too.

Code:

>>> del squares[4]
>>> squares

Output:

{1: 1, 2: 4, 3: 9, 5: 25, 6: 36, 8: 64, 9: 81}

Code:

>>> del squares[10]

Output:

Traceback (most recent call last):
  File “<pyshell#37>”, line 1, in <module>
    del squares[10]
KeyError: 10

You can also delete the complete dictionary with this del keyword.

Code:

>>> cubes={1:1, 2:8, 3:27, 4:64}
>>> del cubes
>>> cubes

Output:

Traceback (most recent call last):
  File “<pyshell#41>”, line 1, in <module>
    cubes
NameError: name ‘cubes’ is not defined

4. clear()

The clear() method does not delete a dictionary, it removes all the key-value pairs from it.

Code:

>>> cubes={1:1, 2:8, 3:27, 4:64}
>>> cubes.clear()
>>> cubes

Output:

{}

Changing Values in Python Dictionaries

Again, dictionaries are mutable and you can change values for different keys.

Code:

>>> cubes={1:1, 2:8, 3:27, 4:64}
>>> cubes[3]=27.0
>>> cubes

Output:

{1: 1, 2: 8, 3: 27.0, 4: 64}

In this example, we change the value of key 3 to 27.0.

Looping on Dictionaries

Like strings and lists, we can loop on dictionaries. If you want to perform an operation for all values in a dictionary, you can use it in a for loop.

Code:

for key,value in squares.items():
    print(key,value)

Output:

1 1
2 4
3 9
5 25
6 36
8 64
9 81

We use the items() method for this to get the key-value pairs for this dictionary.

Code:

for key in squares:
    print(key)

Output:

1
2
3
5
6
8
9

These are the keys in the dictionary.

Code:

for value in squares.values():
    print(value)

Output:

1
4
9
25
36
64
81

And these are the values in this dictionary.

Length and Membership

We can check a dictionary’s length with the len() function.

Code:

>>> len(squares)

Output:

7

If you want to see whether a key is present in a dictionary, you can use the membership operators in and not in.

Code:

>>> 7 in squares

Output:

False

Code:

>>> 8 in squares

Output:

True

Copying Dictionaries in Python

You can copy a dictionary in two ways in Python – using copy() and using dict(). You cannot copy a dictionary by assigning it to a new variable. That creates a reference to the original dictionary, not a copy.

You can copy a dictionary in two ways – copy() and dict().

1. copy()

copy() is an in-built method which creates a shallow copy of a dictionary.

Code:

>>> cubes

Output:

{1: 1, 2: 8, 3: 27.0, 4: 64}

Code:

>>> d=cubes.copy()
>>> d[3]=27
>>> cubes

Output:

{1: 1, 2: 8, 3: 27.0, 4: 64}

2. dict()

dict() creates a dictionary from a different data type or even from a dictionary.

Code:

>>> dict([(1,2),(2,4)])

Output:

{1: 2, 2: 4}

Doing this without parameters gives you an empty dictionary.

Code:

>>> dict()

Output:

{}

Nested Dictionaries and Comprehension

Dictionaries can hold any number of dictionaries.

Code:

>>> groceries={
  'dairy':{
    'milk':20,
    'eggs':15},
  'breads':{
    'bread':10}
  }

This is a nested dictionary.

The groceries dictionary has the dairy and breads dictionaries in it.

Dictionary Comprehension – Like list comprehension, you can use dictionary comprehension to quickly create dictionaries.

Code:

>>> cubes={val:val**3 for val in range(6)}
>>> cubes

Output:

{0: 0, 1: 1, 2: 8, 3: 27, 4: 64, 5: 125}

This dictionary has the cubes of numbers.

Python Dictionary Methodspython dictionaries method

Python has some built-in methods and functions for all data structures. Let’s see what methods we can call on dictionaries.

1. clear()

clear() removes all the key-value pairs of a dictionary.

Code:

>>> cubes={1:1, 2:8, 3:27}
>>> cubes.clear()
>>> cubes

Output:

{}

2. copy()

copy() returns a shallow copy of a dictionary.

Code:

>>> cubes={1:1, 2:8, 3:27}
>>> cubes1=cubes.copy()
>>> cubes1

Output:

{1: 1, 2: 8, 3: 27}

3. fromkeys()

This method takes keys from an iterable and creates a new dictionary from it.

Code:

>>> cubes1=dict.fromkeys([1,2,3],10)
>>> cubes1

Output:

{1: 10, 2: 10, 3: 10}

4. get()

This method gets the value for a key. The default value is None. And it raises a KeyError if the key is not present in the dictionary.

Code:

>>> cubes.get(3)

Output:

27

5. items()

This method returns a list of a dictionary’s key-value pairs.

Code:

>>> cubes.items()

Output:

dict_items([(1, 1), (2, 8), (3, 27)])

You can use this to loop on a dictionary.

6. keys()

This method returns a list of the key’s dictionaries.

Code:

>>> cubes.keys()

Output:

dict_keys([1, 2, 3])

7. setdefault()

This is like get() but adds a key-value pair to a dictionary if it is not in the dictionary.

Code:

>>> cubes.setdefault(4, 10)

Output:

10

Code:

>>> cubes

Output:

{1: 1, 2: 8, 3: 27, 4: 10}

8. update()

update() adds key-value pairs from one dict to another dict.

Code:

>>> cubes={1: 1, 2: 8, 3: 27}
>>> cubes1={4:64, 5:125}
>>> cubes.update(cubes1)
>>> cubes

Output:

{1: 1, 2: 8, 3: 27, 4: 64, 5: 125}

cubes now has the key-value pairs from cubes1 as well.

9. values()

values() returns a list of the values in the dictionary.

Code:

>>> cubes.values()

Output:

dict_values([1, 8, 27, 64, 125])

10. pop()

This removes the given key from a dictionary.

Code:

>>> cubes.pop(3)

Output:

27

Code:

>>> cubes

Output:

{1: 1, 2: 8, 4: 64, 5: 125}

11. popitem()

This removes the last added key-value pair from a dictionary.

Code:

>>> cubes.popitem()

Output:

(5, 125)

Code:

>>> cubes

Output:

{1: 1, 2: 8, 4: 64}

Python Dictionary Functionspython dictionaries function

Dictionaries also have some built-in functions.

Let’s discuss them.

1. all()

This returns True if all keys in a dictionary are True or if the dictionary is empty.

Code:

>>> all(cubes)

Output:

True

Code:

>>> all({})

Output:

True

2. any()

This returns True if at least one key in a dictionary is True.

Code:

>>> any({1:1, False: True})

Output:

True

3. len()

This returns the length of a dictionary.

Code:

>>> len(cubes)

Output:

3

4. sorted()

This returns a sorted version of a dictionary’s keys.

Code:

>>> sorted(cubes)

Output:

[1, 2, 3, 4]

Summary

Dictionaries are Python’s implementation of a knowledge structure that’s more generally referred to as an associative array. A dictionary consists of a set of key-value pairs.

We learned about creating Python dictionaries, accessing, adding, removing, changing, looping, length, membership, copying, nesting, comprehension, methods and dictionary functions.

Now you know what are dictionaries in Python, how to use and manipulate them.