Dictionaries

Dictionaries store objects by key:value pairs. They are MUTABLE.

Make a dictionary

>>> myD = {'food' : 'pizza', 'quantity' : 2, 'price' : 12}

Fetch a value by key

>>> myD['food']
'pizza'

Add 1 to “quantity” value

>>> myD['quantity'] += 1
>>> myD
{'price': 12, 'food': 'pizza', 'quantity': 3}

Number of entries in dictionary

>>> len(myD)
3

Key membership test alternative

>>> 'food' in myD
True

Create keys by assignment

>>> myd = {}
>>> myd['name'] = 'Dan'
>>> myd['age'] = 40
>>> myd['job'] = 'developer'
>>> myd
{'age': 40, 'name': 'Dan', 'job': 'developer'}

Create a dictionary using dict with keyword arguments

>>> dan1 = dict(name = 'Dan', age = 40, job = 'developer')
>>> dan1
{'age': 40, 'name': 'Dan', 'job': 'developer'}

Create a dictionary using dict with zipping.

>>> dan2 = dict(zip(['name', 'age', 'job'], ['Dan', 40, 'developer']))
>>> dan2
{'age': 40, 'name': 'Dan', 'job': 'developer'}

Nesting

>>> dand = {'name' : {'first' : 'Dan', 'last' : 'Dumitrache'},
... 'job' : ['developer', 'accountant', 'statistician'],
... 'age' : 40}
>>> dand
{'age': 40, 'name': {'last': 'Dumitrache', 'first': 'Dan'}, 'job': ['developer', 'accountant', 'statistician']}

Indexing

>>> dand['job']
['developer', 'accountant', 'statistician']

Expand “job” using append.

>>> dand['job'].append('administrator')
>>> dand
{'age': 40, 'name': {'last': 'Dumitrache', 'first': 'Dan'}, 'job': ['developer', 'accountant', 'statistician', 'administrator']}

Assigning new keys

>>> dand['eyes'] = 'blue'
>>> dand
{'age': 40, 'name': {'last': 'Dumitrache', 'first': 'Dan'}, 'eyes': 'blue', 'job': ['developer', 'accountant', 'statistician', 'administrator']}

Testing if a key is present

>>> 'height' in dand
False
>>> 
>>> if not 'height' in dand:
...     print('missing key')
... 
missing key

Sorting keys

>>> key_list = list(dand.keys())
>>> key_list
['age', 'name', 'eyes', 'job']
>>> key_list.sort()
>>> key_list
['age', 'eyes', 'job', 'name']

Iterate through sorted keys with for

>>> for key in key_list:
...     print(key, '->', dand[key])
... 
age -> 40
eyes -> blue
job -> ['developer', 'accountant', 'statistician', 'administrator']
name -> {'last': 'Dumitrache', 'first': 'Dan'}

… or can use the sorted() built-in function …

>>> for key in sorted(dand):
...     print(key, '->', dand[key])
... 
age -> 40
eyes -> blue
job -> ['developer', 'accountant', 'statistician', 'administrator']
name -> {'last': 'Dumitrache', 'first': 'Dan'}

… or … just for fun …

>>> for c in dand:
...     print(c.upper())
... 
AGE
NAME
EYES
JOB

Leave a Reply