Python Dictionary

  • Dictionaries can be used to store key, value pairs in Python for example: {'first_name': 'abhinav', 'last_name': 'upadhay'}
  • Ordering of the items in the dictionary is not guranteed
  • They are good for fast search or lookup operations

Creating an empty dictionary


In [2]:
empty_dictionary = {}
print empty_dictionary


{}

Creating dictionary with values


In [3]:
filled_dictionary = {'first_name': 'abhinav', 'last_name': 'upadhyay'}
print filled_dictionary


{'first_name': 'abhinav', 'last_name': 'upadhyay'}

Adding values to the dictionary


In [4]:
food_menu = {}
food_menu['pizza'] = 300
food_menu['sandwich'] = 30
food_menu['tea'] = 10
print food_menu


{'tea': 10, 'sandwich': 30, 'pizza': 300}

Notice the ordering of the items in the output above

Reading values from a dictionary

Values from the dictionary can be read in exactly the same way, they are stored in it.


In [5]:
pizza_price = food_menu['pizza']
print pizza_price


300

In [6]:
tea_price = food_menu['tea']
print tea_price


10

Deleting item from the dictionary

Dictionaries have the pop() method which can be used to pop/remove a value with the given key


In [10]:
food_menu.pop('tea')
print food_menu


{'sandwich': 30, 'pizza': 300}

Note about the dictionary keys:

Python only allows immutable types to be used as the keys of a dictionary. For example strings, tuples, numbers.

Exercise:

Try to implement an LRU cache using dicts and lists.


In [ ]: