Dictionary

Dictionaries are simple databases for pairs of a key-word and corresponding items. Key can be a string or a number, but needs to be unique. Items can be a single value or complete structure (tuple, list, ...). Dictionaries have no order, stored items can be accessed via the key-word.

# create a new dictionary

>>> d={}

# add values

>>> d['Antje']=('Barcelona',1987)

>>> d['Mike']=('Berlin',1983)

>>> d

{'Antje': ('Barcelona', 1983), 'Mike': ('Berlin', 1987)}

# get value to key-word 'Mike'

>>> d['Mike']

('Berlin', 1987)

# get all keys

sorted(d.keys())

['Antje', 'Mike']

# get all values

sorted(d.values())

[('Barcelona', 1987), ('Berlin', 1983)]

# get size of dictionary (number of entries)

>>> len(d)

2

# remove a selected entry

>>> del d['Antje']

>>> d

{'Mike': ('Berlin', 1987)}

# print all key-value pairs of a dictionary

for k, v in sorted(d.items()):

print(k, v)

# avoid overwriting duplicate key-words

k='Mike'

v=('Berlin',1983)

if k not in d: # add only if not in dictionary already

d[k]=v

# get default string 'unknown' if key not in dictionary

>>> name = 'Mike'

>>> d.get('Mike', 'unknown')

('Berlin', 1983)

>>> d.get('Michael', 'unknown')

'unknown'

# Multi-key combination

d['Antje']['year']='1987'

→ Multiple keys

see also: Lists