# Dictionaries¶

Dictionary is a set of key-value pair, where value is any hashable object. As Lists are indexed by integers, Dictionries are indexed by keys.

## Creating a Dictionaries¶

• Creating an Empty Dictionary

x = {}      # {} denotes dictionary type (not set)
x = dict()

• Creating Dictionary with initial values

x = {'eight':8,'nine':9}

In :

x = {'eight':8,'nine':9}

In :

x['eight']

Out:

8

In :

x

--------------------------------------------------------------------------
KeyError                                 Traceback (most recent call last)
<ipython-input-3-1ae75c28907a> in <module>()
----> 1 x

KeyError: 0


If a key is not present in Dictionary, KeyError is raised

In :

x['zero'] = 0 # Adding a key-value to dictionary
x

Out:

{'eight': 8, 'nine': 9, 'zero': 0}

In :

del x['nine']  # Deleting based on key
x

Out:

{'eight': 8, 'zero': 0}

In :

'zero' in x    # Only key membership can be checked

Out:

True


## Dictionary Methods¶

If d is a dictionary

• d.keys() returns a view of d’s keys
• d.values() returns a view of d’s values
• d.items() returns a view of d’s key-value pairs
In :

x

Out:

{'eight': 8, 'zero': 0}

In :

x.keys()

Out:

dict_keys(['eight', 'zero'])

In :

x.values()

Out:

dict_values([8, 0])

In :

x.items()

Out:

dict_items([('eight', 8), ('zero', 0)])

In :

for k,v in x.items():
print("{}={}".format(k,v))

eight=8
zero=0


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.