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.
Dictionaries can be initiated in many ways:
d = {} # empty dict
d = {'key': 'value'} # dict with initial values
# 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}
d = {k:v for k,v in [('key', 'value',)]}
see also: Comprehensions
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)
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']