Search notes:

Python: dict

A dict is a container.

Creating a dict

A dictionary can be created with curly braces that contain the items.
The items are separated by commas.
Each item consists of the key separated from the value by a colon (:):
empty_dict = {}
another_dict = {
  'one'              :  1,
  (42, 'hello world'): 'foo, bar and baz',
   99                : 'Nena'} 

print(type(empty_dict  ))
#
#  <class 'dict'>

print(type(another_dict))
#
#  <class 'dict'>
Github repository about-python, path: /types/dict/create-curly-braces.py
A dict can be created from a sequence whose items are sequences themselves that provide the key/value pairs.
seq = [
  ( 'Key'        , 'Value'         ),
  [ 'Another key', 'Another Value' ]
]

d = dict(seq)

for k, v in d.items():
    print(k, ':', v)
#
#  Key : Value
#  Another key : Another Value
Github repository about-python, path: /types/dict/create-from-sequence.py
If the keys are strings, a dict can be with keyword arguments:
d = dict(one = 1, two = 2, three = 3)

for k, v in d.items():
    print('{:5s}: {}'.format(k, v))
#
#  one  : 1
#  two  : 2
#  three: 3
Github repository about-python, path: /types/dict/create-keyword-arguments.py
A dict can also be created with a dict comprehension.

Looking up values/elements

The value for a key can be looked up with square brackets dict[key]. If the key does not exist, the interpreter raises a KeyError exception.
d = { 'num': 42, 'txt': 'Hello world' }

def printValOfKey(k):

    try:
       print(f'value for {k} is: {d[k]}')
    except KeyError:
       print(f'Key {k} does not exist')


printValOfKey('num'       )
printValOfKey('inexistent')
printValOfKey('txt'       )
Github repository about-Python, path: /types/dict/lookup/square-brackets.py
Alternatively, a value can also be looked up with the get method.
It comes in two forms: dict.get(key) and dict.get(key, defaultValue). The first variant returns None if the key does not exist, the second one returns defaultValue if the key does not exist.
d = { 'num': 42, 'txt': 'Hello world' }

def printValOfKey(k):
    print(f"value for {k} is: {d.get(k, '?')}")

printValOfKey('num'       )
printValOfKey('inexistent')
printValOfKey('txt'       )
Github repository about-Python, path: /types/dict/lookup/get.py

A dict is a mapping, not a sequence

Although a dict implements __getitem__() and __len__(), it is considered a mapping type rather than a sequence type.
This is because the items a dict contains are looked up with immutable keys rather than integers.

Check if a given key exists

The in operator returns true if a given key exists in a dictionary and false otherwise:
#!/usr/bin/python

d = {'foo': 'abc', 'baz': 'def'}

for k in ['foo', 'bar', 'baz']:
    if k in d:
       print('Key {:s} exists, val is {:s}'.format(k, d[k]))
    else:
       print('Key {:s} does not exist'.format(k))
Github repository about-python, path: /types/dict/check-if-key-exists.py

Getting keys of a dictionary

keys() returns a list that contains a dictionary's keys:
d = {'foo': 42, 'bar': "forty-two", 'baz': None}

print("\n".join (d.keys()))
# baz
# foo
# bar
Github repository about-python, path: /types/dict/keys.py
list() also returns a list of the dictionary's keys. The returned list is ordered according to the insertion of the elements into the dictionary:
d = dict()
d['first' ] = 'one'
d['second'] =    2
d['third' ] = ['*', '*', '*']

print(list(d))
#
#  ['first', 'second', 'third']
Github repository about-python, path: /types/dict/list.py

Iterating over keys and values of a dictionary

items() can be used to iterate over keys and values from a dictionary:
#!/usr/bin/python

d = {'foo':  42, 
     'bar': "forty-two",
     'baz': None}

for k,v in d.items():
    print(k, " = ", v)
Github repository about-python, path: /types/dict/items.py

Removing keys from a dict

A key/value pair can be removed from a dict with del(dct[ix]) (see here).

Allowed key types

A dict only allows immutable objects as keys.
Therefore, tuples are allowed as keys, but not lists.
Using a tuple as a key:
>>> x = {(1,2,3): 'foo'}
>>> x[(1,2,3)]
'foo'
Trying to use a list as a key:
>>> y = {[1,2,3]: 'bar'}
…
TypeError: unhashable type: 'list'

Dict comprehension

A dictionary can be created with a dict comprehension.
d = { word: len(word) for word in ['one', 'two', 'three', 'four', 'five', 'six'] }

for k, v in d.items():
    print('{:5s}: {}'.format(k, v))
#
#  one  : 3
#  two  : 3
#  three: 5
#  four : 4
#  five : 4
#  six  : 3
Github repository about-python, path: /types/dict/comprehension.py
Compare with list comprehensions.

Implementation of dicts

A dict is implemented as a resizable hash table which is claimed to have better performance than a B-tree when looking up elements. In fact, this takes a constant time: O(1).

See also

Adding key-value pairs to a dictionary
Copying a dictionary (rather than aliasing it).
Using the update() method of a dict to update it from the key/value pairs from another dict.
Merge two dictionaries
The collections module:
Sets might also be created with curly braces.

Index