Python’s Most Powerful Data Type

Everything you ever need to know about Python dictionaries

Photo by Syd Wachs on Unsplash.

The dictionary is one of Python’s most powerful data types. In other programming languages and computer science in general, dictionaries are also known as associative arrays. This is because they allow you to associate keys with values.

Creating a Dictionary

Let’s look at how we can create and use a dictionary in the Python REPL:

>>> phone_nrs = { 'Jack': '070-02222748', 'Pete': '010-2488634' }
>>> an_empty_dict = { }
>>> phone_nrs['Jack']

The first dictionary associates keys (names like Jack and Pete) with values (their phone numbers). The second dictionary is an empty one.

Now that you’ve seen how to initialize a dictionary, let’s see how we can add and remove entries to an already existing one:

>>> phone_nrs['Eric'] = '06-10101010'
>>> del(phone_numbers['Jack'])
>>> phone_nrs
{'Pete': '010-2488634', 'Eric': '06-10101010'}

Valid Dictionary Values

You can put anything in a dictionary. You’re not limited to numbers or strings. In fact, you can put dictionaries and lists inside your dictionary and access the nested values in a very natural way:

>>> a = { 'sub_dict': { 'b': True }, 'mylist': [100, 200, 300] }
>>> a['sub_dict']['b']
>>> a['mylist'][0]

Python’s JSON decoding and encoding library uses this Python feature when parsing more complex JSON documents. It creates nested trees of lists, dictionaries, and other valid data types.

Valid Dictionary Keys

If you want, you can go rather crazy on your dictionary keys too. The only requirement is that the key is of an immutable data type. Hench, mutable types like lists, dictionaries, and sets won’t work.

Besides this limitation, you can use all data types as a dictionary key, including native types like float and int. Although this might be completely useless for most of you, I'll demonstrate anyway:

>>> crazy_dictionary = { int: 1, float: 2, dict: 3 }
>>> crazy_dictionary[dict]

A more likely use case is the use of numbers as keys (e.g., to register runners in a marathon):

>>> runners = { 1000: 'Jack', 1001: 'Eric', 1002: 'Lisa' }
>>> runners[1001]

More Ways to Initialize a Dictionary

There are more advanced ways to initialize a dictionary that might come in handy, depending on the source of your data.

Using the dict() constructor

The dict() function builds a dictionary from a sequence or list of key-value pairs:

>>> dict([ ('Jack', '070-02222748'), ('Pete', '010-2488634'), ('Eric', '06-10101010') ])
{'Jack': '070-02222748', 'Pete': '010-2488634', 'Eric': '06-10101010'}

Dictionary comprehensions

Analogous to list comprehensions, you can also use dictionary comprehensions to create a new dictionary:

>>> {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}

Using dict.fromkeys

The dict.fromkeys(keys, value) method creates a new dictionary based on the list of keys supplied to it. The value of all elements will be set to the supplied value or None by default, if you don't supply a value:

>>> names = ('Eric', 'Martha', 'Ellen')
>>> phone_numbers = dict.fromkeys(names, None)
>>> phone_numbers
{'Ellen': None, 'Eric': None, 'Martha': None}

Parse a JSON dictionary

You can also decode JSON data into a dictionary like this:

>>> import json
>>> jsonstring = '{"name": "erik", "age": 38, "married": true}'
>>> json.loads(jsonstring)
{'name': 'erik', 'age': 38, 'married': True}

Using Dictionaries

Dictionary view objects

Some built-in dictionary methods return a view object, offering a window on your dictionary’s key and values. Values in a view object change as the content of the dictionary changes. This is best illustrated with an example:

phone_numbers = { 'Jack': '070-02222748', 'Pete': '010-2488634', 'Eric': '06-10101010' }
names = phone_numbers.keys()
phone_numbers['Linda'] = 9876

The output of this code is dict_keys(['Jack', 'Pete', 'Eric', 'Linda']). As you can see, Linda is part of the list, too, even though she got added after creating the names view object.

Access and delete a single key/value pair

We’ve already seen how to access and delete a single key-value pair:

>>> phone_numbers['Eric'] = '06-10101010'
>>> del(phone_numbers['Jack'])

To overwrite an entry, assign a new value to it. You don’t need to del() it first.

If the requested key does not exist, an exception of the type KeyError is thrown:

>>> phone_numbers['lisa']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'lisa'

If you know data can be missing (e.g., when parsing input from the outside world), make sure to surround your code with a try ... except.

Get all the keys from a dictionary

There are two easy ways to get all the keys from a dictionary:

list() returns all the keys in insertion order, while sorted() returns all the keys sorted alphabetically.

There’s also the dict.keys() method that returns a view object containing a list of all the dictionary keys. The advantage of this object is that it stays in sync with the dictionary. It's perfect for looping over all the keys, but you still might opt for the list or sorted methods, though, because those return a native list that you can manipulate as well.

Check if a key exists in a dictionary

You can check if a key exists inside a dictionary with the in and not in keywords:

>>> 'Jack' in phone_numbers
>>> 'Jack' not in phone_numbers

Getting the length of a dictionary

The len() returns the number of key-value pairs in a dictionary:

>>> phone_numbers = { 'Jack': '070-02222748', 'Pete': '010-2488634', 'Eric': '06-10101010' }
>>> len(phone_numbers)

Looping through a dictionary

The items() method of a dictionary returns an iterable view object, as can be seen below. You can loop through this object with a simple for loop:

Built-In Dictionary Methods

Each dictionary inherits handy built-in functions. I’ll list the more interesting and useful ones here:

  • clear() — Remove all key-value pairs (empty the dictionary). For example, phone_nrs.clear().
  • get(key) — Get a single item with a given key, with an optional default value (e.g. phone_nrs.get(‘Martha’, ‘Unknown person’)).
  • items() — Returns a view object containing key-value pairs from the dictionary (e.g. phone_nrs.items()).
  • keys() — Returns a view object with a list of all keys from the dictionary (e.g. phone_numbers.keys()).
  • values() — Returns a view object with a list of all values from the dictionary (e.g. phone_numbers.values()).
  • pop(key, default_value) — Returns and removes the element with the specified key (e.g. phone_numbers.pop(‘Martha’)).
  • popitem() — Returns and removes the last inserted item (Python 3.7+) or a random item (e.g. phone_numbers.popitem()).
  • setdefault(key, value)— Returns the value of the specified key. If the key does not exist, it’s inserted with the given value (e.g. phone_numbers.setdefault(‘John Doe’, 1234)).
  • update(iterable) — Add all pairs from given iterable (e.g. phone_numbers.update({“Alina”: 1234, “Alice”, 2345})).

Software developer by day, writer at night. Webmaster at

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store