Python Basic Data Structure — Dictionary




Dictionary







In this part, we will show examples of dictionary. Dictionary provides a way for you to map a specific value to another one.

In [2]:
my_dict = {"1":1,"2":2}
print my_dict
{'1': 1, '2': 2}

Different than list, dictionary require the get method for its elements

In [4]:
my_dict.get("1")
Out[4]:
1
In [20]:
my_dict.update({"1":2})

You can use copy method to define a new dictionary

In [21]:
new_dict = my_dict.copy()
print new_dict
{'1': 2, '2': 2}

You can use iterkeys method to get the iternerator of keys, and wrap a list function to get the list value.

In [22]:
print (list(new_dict.iterkeys()))

print (list(new_dict.itervalues()))
['1', '2']
[2, 2]
In [30]:
new_dict["3"] =3
print new_dict
{'1': 2, '3': 3, '2': 2}