Define simple printing functions


In [1]:
from __future__ import print_function

import json 

def print_dict(dd): 
    print(json.dumps(dd, indent=2))

Constructing and allocating dictionaries

The syntax for dictionaries is that {} indicates an empty dictionary


In [2]:
d1 = dict() 
d2 = {}

print_dict(d1)
print_dict(d2)


{}
{}

There are multiple ways to construct a dictionary when the key/value pairs are known beforehand. The following two snippets are equivalent.


In [3]:
d3 = {
    'one': 1, 
    'two': 2
}

print_dict(d3)


{
  "one": 1,
  "two": 2
}

In [4]:
d4 = dict(one=1, two=2)

print_dict(d4)


{
  "one": 1,
  "two": 2
}

Often an ordered list of keys and values are available as lists, and it is desirable to create a dictionary from these lists. There are a number of ways to do this, including:


In [5]:
keys = ['one', 'two', 'three']
values = [1, 2, 3]

d5 = {key: value for key, value in zip(keys, values)}
print_dict(d5)


{
  "one": 1,
  "two": 2,
  "three": 3
}

Adding new data to the dict


In [6]:
d1['key_1'] = 1
d1['key_2'] = False

print_dict(d1)


{
  "key_1": 1,
  "key_2": false
}

Dictionaries are a dynamic data type, and any object can be used as a value type, including integers, floats, lists, and other dicts, for example:


In [7]:
d1['list_key'] = [1, 2, 3]
print_dict(d1)


{
  "key_1": 1,
  "key_2": false,
  "list_key": [
    1,
    2,
    3
  ]
}

In [8]:
d1['dict_key'] = {'one': 1, 'two': 2}
print_dict(d1)


{
  "key_1": 1,
  "key_2": false,
  "list_key": [
    1,
    2,
    3
  ],
  "dict_key": {
    "one": 1,
    "two": 2
  }
}

In [9]:
del d1['key_1']
print_dict(d1)


{
  "key_2": false,
  "list_key": [
    1,
    2,
    3
  ],
  "dict_key": {
    "one": 1,
    "two": 2
  }
}

Accessing the data

It is always possible to get access to the key/value pairs that are contained in the dictionary, and the following functions help with this:


In [10]:
print(d1.keys())


dict_keys(['key_2', 'list_key', 'dict_key'])

In [12]:
for item in d1:
    print(item)


key_2
list_key
dict_key

In [13]:
d1['dict_key']['one']


Out[13]:
1

Iterating over key/values

The following two cells are nearly equivalent. In order to understand how they differ, it will be helpful to confer with Python documentation on iterators and generators http://anandology.com/python-practice-book/iterators.html


In [14]:
for key, value in d1.items(): 
    print(key, value)


key_2 False
list_key [1, 2, 3]
dict_key {'one': 1, 'two': 2}

In [16]:
for key, value in d1.iteritems():  # Only in Python2 (.items() returns an iterator in Python3)
    print(key, value)


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-16-0ed84a7a47a2> in <module>()
----> 1 for key, value in d1.iteritems():  # Only in Python2 (.items() returns an iterator in Python3)
      2     print(key, value)

AttributeError: 'dict' object has no attribute 'iteritems'

In [17]:
print(d1.keys())
print(d1.values())


dict_keys(['key_2', 'list_key', 'dict_key'])
dict_values([False, [1, 2, 3], {'one': 1, 'two': 2}])

Filtering and mapping dictionaries


In [19]:
def dict_only(key_value): 
    return type(key_value[1]) is dict

print('All dictionary elements:')
print(list(filter(dict_only, d1.items())))


All dictionary elements:
[('dict_key', {'one': 1, 'two': 2})]

In [20]:
print('Same as above, but with inline function (lambda):')
print(filter(lambda key_value: type(key_value[1]) is dict, d1.items()))


Same as above, but with inline function (lambda):
<filter object at 0x10d57ac50>

In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]: