Dictionary is a set of key-value pairs, where value is any hashable object. As Lists are indexed by integers, Dictionries are indexed by keys.
x = {} # {} denotes dictionary type (not set)
x = dict()
x = {'eight':8,'nine':9}
In [1]:
x = {'eight':8,'nine':9}
In [2]:
x['eight']
Out[2]:
In [3]:
x[0]
If a key is not present in Dictionary, KeyError
is raised
In [4]:
x['zero'] = 0 # Adding a key-value to dictionary
x
Out[4]:
In [5]:
del x['nine'] # Deleting based on key
x
Out[5]:
In [6]:
'zero' in x # Only key membership can be checked
Out[6]:
In [7]:
x
Out[7]:
In [8]:
x.keys()
Out[8]:
In [9]:
x.values()
Out[9]:
In [10]:
x.items()
Out[10]:
In [12]:
for k,v in x.items():
print("{} = {}".format(k,v))
Dictionary Values can be any hashable object. This means they can be lists, tuples,... . Using Dictionaries, one can implement an Adjacency List Representation of Graph Data Structure.