In [1]:
from __future__ import print_function
import json
def print_dict(dd):
print(json.dumps(dd, indent=2))
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)
In [4]:
d4 = dict(one=1, two=2)
print_dict(d4)
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)
In [6]:
d1['key_1'] = 1
d1['key_2'] = False
print_dict(d1)
Dictionaries are a dynamic data type, and any object can be used as a value type, including integers
, float
s, list
s, and other dict
s, for example:
In [7]:
d1['list_key'] = [1, 2, 3]
print_dict(d1)
In [8]:
d1['dict_key'] = {'one': 1, 'two': 2}
print_dict(d1)
In [9]:
del d1['key_1']
print_dict(d1)
In [10]:
print(d1.keys())
In [12]:
for item in d1:
print(item)
In [13]:
d1['dict_key']['one']
Out[13]:
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)
In [16]:
for key, value in d1.iteritems(): # Only in Python2 (.items() returns an iterator in Python3)
print(key, value)
In [17]:
print(d1.keys())
print(d1.values())
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())))
In [20]:
print('Same as above, but with inline function (lambda):')
print(filter(lambda key_value: type(key_value[1]) is dict, d1.items()))
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]: