Python Dictionaries

A dictionary is like a list, but more general. In a list, the index positions have to be integers; in a dictionary, the indices can be (almost) any type. Dictionary as a mapping between a set of indices (which are called keys) and a set of values. Each key maps to a value.

The association of a key and a value is called a key-value pair or sometimes an item. As an example, we’ll build a dictionary that maps from English to German words, so the keys and the values are all strings.

How to create a dictionary?

The function dict creates a new dictionary with no items. Because dict is the name of a built-in function, you should avoid using it as a variable name.

eng2gr = dict()
print(eng2gr)

The curly brackets, {}, represent an empty dictionary. To add items to the dictionary, you can use square brackets:

eng2gr['one'] = 'eins'

This line creates an item that maps from the key ’one’ to the value “eins”. If you print the dictionary again, you see a key-value pair with a colon between the key and value:

print(eng2gr)

This output format is also an input format. For example, you can create a new dictionary with three items. But if you print eng2gr, you might be surprised:

eng2gr = {'one': 'eins', 'two': 'zwei', 'three': 'drei'}
print(eng2gr)
Try it Yourself

How to access elements from a dictionary?

The order of the key-value pairs is not the same. In fact, if you type the same example on your computer, you might get a different result. In general, the order of items in a dictionary is unpredictable. But that’s not a problem because the elements of a dictionary are never indexed with integer indices. Instead, you use the keys to look up the corresponding values:

eng2gr = {'one': 'eins', 'two': 'zwei', 'three': 'drei'}
print(eng2gr['two'])

The key ’two’ always maps to the value “zwei” so the order of the items doesn’t matter.If the key isn’t in the dictionary, you get an exception:

>>> print(eng2gr['four'])
KeyError: 'four'

While indexing is used with other container types to access values, dictionary uses keys. 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.

print(eng2gr.get('two'))
print(eng2gr.get('three'))

The len function works on dictionaries; it returns the number of key-value pairs:

len(eng2gr)

How to change or add elements in a 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.

eng2gr = {'one': 'eins', 'two': 'zwei', 'three': 'drei'}
eng2gr['four'] = 'four' #Add Element
print(eng2gr)
eng2gr['four'] = 'vier'  #Update Element
print(eng2gr)
Try it Yourself

Dictionary Membership Test

The in operator works on dictionaries; it tells you whether something appears as a key in the dictionary.

>>> 'one' in eng2gr
True
>>> 'eins' in eng2gr
False

To see whether something appears as a value in a dictionary, you can use the method values, which returns the values as a list, and then use the in operator:

vals = list(eng2gr.values())
>>>'eins' in vals
True
Try it Yourself

The in operator uses different algorithms for lists and dictionaries. For lists, it uses a linear search algorithm. As the list gets longer, the search time gets longer in direct proportion to the length of the list. For dictionaries, Python uses an algorithm called a hash table that has a remarkable property: the in operator takes about the same amount of time no matter how many items there are in a
dictionary. I won’t explain why hash functions are so magical, but you can read more about it at wikipedia.org/wiki/Hash_table.

How to delete or remove elements from a dictionary?

You 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.

You can also use the del keyword to remove individual items or the entire dictionary itself.

eng2gr = {'one': 'eins', 'two': 'zwei', 'three': 'drei', 'four':'vier'}
# remove a particular item
print(eng2gr.pop('four'))
print(eng2gr)

# remove an arbitrary item
print(eng2gr.popitem())
print(eng2gr)

# delete a particular item
del eng2gr['one']
print(eng2gr)

# remove all items
eng2gr.clear()
Try it Yourself

Python Dictionary Methods

Methods that are available with dictionary are tabulated below. Some of them have already been used in the above examples.

Python Dictionary Methods
Method Description
clear() Remove all items form the dictionary.
copy() Return a shallow copy of the dictionary.
fromkeys(seq[, v]) Return a new dictionary with keys from seq and value equal to v(defaults to None).
get(key[,d]) Return the value of key. If key doesnot exit, return d (defaults to None).
items() Return a new view of the dictionary’s items (key, value).
keys() Return a new view of the dictionary’s keys.
pop(key[,d]) Remove the item with key and return its value or d if key is not found. If d is not provided and key is not found, raises KeyError.
popitem() Remove and return an arbitary item (key, value). Raises KeyError if the dictionary is empty.
setdefault(key[,d]) If key is in the dictionary, return its value. If not, insert key with a value of d and return d (defaults to None).
update([other]) Update the dictionary with the key/value pairs from other, overwriting existing keys.
values() Return a new view of the dictionary’s values

 

Here are a few example use of these methods.

fruits = {}.fromkeys(['Orange','Apple','Banana'], 0)
print(fruits)

for item in fruits.items():
    print(item)

list(sorted(fruits.keys()))
Try it Yourself

Dictionary as a set of counters

 

Dictionaries and files

Looping and dictionaries

Python Lists