Python Language Introduction to Dictionary


Example

A dictionary is an example of a key value store also known as Mapping in Python. It allows you to store and retrieve elements by referencing a key. As dictionaries are referenced by key, they have very fast lookups. As they are primarily used for referencing items by key, they are not sorted.

creating a dict

Dictionaries can be initiated in many ways:

literal syntax

d = {}                        # empty dict
d = {'key': 'value'}          # dict with initial values
Python 3.x3.5
# Also unpacking one or multiple dictionaries with the literal syntax is possible

# makes a shallow copy of otherdict
d = {**otherdict}
# also updates the shallow copy with the contents of the yetanotherdict.
d = {**otherdict, **yetanotherdict}

dict comprehension

d = {k:v for k,v in [('key', 'value',)]}

see also: Comprehensions

built-in class: dict()

d = dict()                    # emtpy dict
d = dict(key='value')         # explicit keyword arguments
d = dict([('key', 'value')])  # passing in a list of key/value pairs
# make a shallow copy of another dict (only possible if keys are only strings!)
d = dict(**otherdict)         

modifying a dict

To add items to a dictionary, simply create a new key with a value:

d['newkey'] = 42

It also possible to add list and dictionary as value:

d['new_list'] = [1, 2, 3]
d['new_dict'] = {'nested_dict': 1}

To delete an item, delete the key from the dictionary:

del d['newkey']