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
Alternatively, a value can also be looked up with the getmethod.
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' )
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))
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
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).