A python dictionary is a data structure similar to an associative array found in other programming languages. An array or a list indexes elements by position. A dictionary, on the other hand, indexes elements by keys which can be strings. Think of a dictionary as unordered sets of key-value pairs.

a python dictionary key-value pairs

In this article, we introduce you to working with the python dictionary.

Creating a Dictionary

There are several ways of creating a python dictionary. The simplest uses brace initialization, with a syntax reminiscent of JSON.

        users = {'firstname': 'John', 'lastname': 'Smith', 'age': 27}

You can use numbers too as the keys. However, be careful using floating point numbers as keys, since the computer stores these as approximations.

        rain_percent = { 1980: '17%', 1981: '15%', 1982: '10%'}
print(rain_percent)
print(rain_percent[1980])
# prints
{1980: '17%', 1981: '15%', 1982: '10%'}
17%

Specifying Key-Value Pairs

You can also create and initialize a dictionary using name value pairs as keyword arguments to the dict() constructor.

        population = dict(California=37253956, Colorado=5029196, Connecticut=3574097, Delaware=897934)
print(population)
# prints
{'Connecticut': 3574097, 'Delaware': 897934, 'California': 37253956, 'Colorado': 5029196}

Array of Key-Value Tuples

Yet another way of creating a dictionary is to use an array of key-value tuples. Here is the same example as above.

        pairs = [('California', 37253956), ('Colorado', 5029196), ('Connecticut', 3574097), ('Delaware', 897934)]
population = dict(pairs)
print(population)
# prints
{'Connecticut': 3574097, 'Delaware': 897934, 'California': 37253956, 'Colorado': 5029196}

Dict Comprehension

Dict comprehension provides a cool syntax to initialize a dict if you can compute the values based on the keys. The following initializes a dict of numbers and square values for a range of numbers.

        print({x: x**2 for x in xrange(10, 20)})
# prints
{10: 100, 11: 121, 12: 144, 13: 169, 14: 196, 15: 225, 16: 256, 17: 289, 18: 324, 19: 361}

How does it work? The latter part (for x in xrange(10, 20)) returns a range of numbers in the specified range. The dict comprehension part ({x: x**2 ..}) loops over this range and initializes the dictionary.

Working With a Python Dictionary

What can you do with dictionaries once you have created them? Well, you can access elements, update values, delete elements, etc.

Accessing Python Dictionary Elements

Access an element of a dict using the key within brackets, just like you would an array or a list.

        print(population['Delaware'])
# prints
897934

If the key is a number, you don't need the quotes. The expression then appears to look like a list or array indexing.

        print(rain_percent[1980])
# prints
17%

The type of the key when accessing it must match what is stored in the Python dictionary. The following causes an error since the stored keys are numbers while the access key is a string.

        x = '1980'
print(rain_percent[x])
# results in
      1 x = '1980'
----> 2 print(rain_percent[x])

KeyError: '1980'

Accessing a non-existent key is an error.

        rain_percent = { 1980: '17%', 1981: '15%', 1982: '10%'}
print(rain_percent[1983])
# prints
      1 rain_percent = { 1980: '17%', 1981: '15%', 1982: '10%'}
----> 2 print(rain_percent[1983])

KeyError: 1983

To access a key and provide a default value if the mapping does not exist, use the get() method with default value as the second argument.

        print(rain_percent.get(1985, '0%'))
# prints
0%

Checking for Existence

What if you want to check for the presence of a key without actually attempting to access it (and possibly encountering a KeyError as above)? You can use the in keyword in the form key in dct which returns a boolean.

        print(1980 in rain_percent)
print('1980' in rain_percent)
# prints
True
False

Reverse the condition (i.e. ensure that the key is not present in the Python dictionary) using the form key not in dct. This is equivalent to the standard python negation not key in dct.

        print(1980 not in rain_percent)
print(1985 not in rain_percent)
# prints
False
True

Modifying Elements

Change the value by assigning to the required key.

        users = {'firstname': 'John', 'lastname': 'Smith', 'age': 27}
users['age'] = 29
print(users)
# prints
{'lastname': 'Smith', 'age': 29, 'firstname': 'John'}

Use the same syntax to add a new mapping to the Python dictionary.

        users['dob'] = '15-sep-1971'
print(users)
# prints
{'dob': '15-sep-1971', 'lastname': 'Smith', 'age': 29, 'firstname': 'John'}

Update multiple elements of a dictionary in one shot using the update() method.

        users = {'firstname': 'John', 'lastname': 'Smith', 'age': 27}
users.update({'age': 29, 'dob': '15-sep-1971'})
print(users)
# prints
{'dob': '15-sep-1971', 'lastname': 'Smith', 'age': 29, 'firstname': 'John'}

Set a default value for a key using setdefault(). This method sets the value for the key if the mapping does not exist. It returns the current value.

        # does not change current value
print(users.setdefault('firstname', 'Jane'))
# prints
John

# sets value
print(users.setdefault('city', 'NY'))
# prints
NY

# Final value
print(users)
# prints
{'lastname': 'Smith', 'age': 27, 'firstname': 'John', 'city': 'NY'}

Deleting elements

Delete mappings in the dictionary by using the del operator. This operator does not return anything.

You will encounter a KeyError if the key does not exist in the dictionary.

        users = {'firstname': 'John', 'lastname': 'Smith', 'age': 27}
del users['age']
print(users)
# prints
{'lastname': 'Smith', 'firstname': 'John'}

Use the pop() method instead, when you want the deleted value back.

        users = {'firstname': 'John', 'lastname': 'Smith', 'age': 27}
print(users.pop('age'))
print(users)
# prints
27
{'lastname': 'Smith', 'firstname': 'John'}

What if you want to delete a key if it exists, without causing an error if it doesn't? You can use pop() and specify None for second argument as follows:

        users = {'firstname': 'John', 'lastname': 'Smith', 'age': 27}
users.pop('foo', None)
print(users)
# prints
{'lastname': 'Smith', 'age': 27, 'firstname': 'John'}

And here is a one-liner to delete a bunch of keys from a dictionary without causing an error on non-existent keys.

        users = {'firstname': 'John', 'lastname': 'Smith', 'age': 27, 'dob': '15-sep-1971'}
map(lambda x : users.pop(x, None),['age', 'foo', 'dob'])
print(users)

Want to delete all keys from a dictionary? Use the clear() method.

        users = {'firstname': 'John', 'lastname': 'Smith', 'age': 27}
users.clear()
print(users)
# prints
{}

Looping With Python Dictionaries

Python provides many methods for looping over the entries of a dictionary. Pick one to suit your need.

Looping Over Keys

  • The simplest method for processing keys (and possibly values) in sequence uses a loop of the form:
            users = {'firstname': 'John', 'lastname': 'Smith', 'age': 27}
    for k in users:
      print(k, '=>', users[k])
    # prints
    lastname => Smith
    age => 27
    firstname => John
  • Using the method iterkeys() works exactly the same as above. Take your pick as to which form you want to use.
            users = {'firstname': 'John', 'lastname': 'Smith', 'age': 27}
    for k in users.iterkeys():
      print(k, '=>', users[k])
    # prints
    lastname => Smith
    age => 27
    firstname => John
  • A third method to retrieve and process keys in a loop involves using the built-in function iter().
            users = {'firstname': 'John', 'lastname': 'Smith', 'age': 27}
    for k in iter(users):
      print(k, '=>', users[k])
    # prints
    lastname => Smith
    age => 27
    firstname => John
  • When you need the index of the key being processed, use the enumerate() built-in function as shown.
            users = {'firstname': 'John', 'lastname': 'Smith', 'age': 27}
    for index, key in enumerate(users):
      print(index, key, '=>', users[k])
    # prints
    0 lastname => John
    1 age => John
    2 firstname => John

Looping Over Key-Value Pairs

  • When you want to retrieve each key-value pair with a single call, use iteritems().
            users = {'firstname': 'John', 'lastname': 'Smith', 'age': 27}
    for k, v in users.iteritems():
      print(k, '=>', v)
    # prints
    lastname => Smith
    age => 27
    firstname => John

Iterating Over Values

  • The method itervalues() can be used to iterate over all the values in the dictionary. Though this method looks similar to a loop using values(), it is more efficient since it does not extract all the values at once.
            users = {'firstname': 'John', 'lastname': 'Smith', 'age': 27}
    for value in users.itervalues():
      print(value)
    # prints
    Smith
    27
    John

Extracting Arrays

The following methods describe extracting various Python dictionary information in an array form. The resulting array can be looped over using normal python constructs. However, keep in mind that the returned array can be large depending on the size of the dictionary. So it might be more expensive (memory-wise) to process these arrays than using the iterator methods above.

One case where it is acceptable to work with these arrays is when you need to delete items from the dictionary as you encounter undesirable elements. Working with an iterator while modifying the dictionary may cause a RuntimeError.

  • The method items() returns an array of key-value tuples. You can iterate over these key-value pairs as shown:
            users = {'firstname': 'John', 'lastname': 'Smith', 'age': 27}
    for k, v in users.items():
      print(k, '=>', v)
    # prints
    lastname => Smith
    age => 27
    firstname => John
  • Retrieve all the keys in the dictionary using the method keys().
            users = {'firstname': 'John', 'lastname': 'Smith', 'age': 27}
    print(users.keys())
    # prints
    ['lastname', 'age', 'firstname']
    Use the returned array to loop over the keys.
            for k in users.keys():
      print(k, '=>', users[k])
    # prints
    lastname => Smith
    age => 27
    firstname => John
  • In a similar way, use the method values() to retrieve all the values in the dictionary.
            for value in users.values():
      print(value)
    # prints
    Smith
    27
    John

How Do You Use Python Dictionaries?

We have tried to cover the most common use cases for python dictionaries in this article. Make sure to check out all of our other Python articles for even more Python tips. If you have other use cases you feel should be included, please let us know in the comments below!

Image Credits: viper345/Shutterstock