Dictionary

Data structures

Dictionaries are simple databases for pairs of key (ID, name) and related values (data). Key can be a string or a number, but needs to be unique. Values can be a single number, string, or a complete structure (tuple, list, ...). Dictionaries have no order, stored items can be accessed via the key-identifier.

# create a new dictionary

d={}

# add values

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

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

d

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

# get value of key identifier '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)}

# empty the entire dictionary  (remove all entries)

d.clear()

d

 {}


# print all key-value pairs of a dictionary

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

    print(k, v)


# avoid overwriting duplicates of key identifier

k='Mike'

v=('Berlin',1983)

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

    d[k]=v


# avoid KeyError (key not found)

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

name = 'Mike'

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

 ('Berlin', 1983)

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

 'unknown'


Read more

# Multi-key combination

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

→ Multiple keys


# Simple list data-structure

mylist = ['Antje', 'Mike', 'Michel']

Lists