Tuesday, March 28, 2017

Dictionary in Python

A dictionary is a dictionary. It's a lookup and contains key value pair. Dictionaries are mutable.

#create an empty dictionary
>>> capital = {}

@asssign elements to the dictionary
>>> capital['India'] = 'Delhi'
>>> capital['Germany'] = 'Berlin'

#print the dictionary
>>> capital
{'Germany': 'Berlin', 'India': 'Delhi'}

#Show all the keys
>>> capital.keys()

['Germany', 'India']

#show all values
>>> capital.values()

['Berlin', 'Delhi']

#show both key value pair
>>> capital.items()
[('Germany', 'Berlin'), ('India', 'Delhi')]

#check if key exists
>>> capital.has_key('Germany')

#Making a deep copy. Changing in copy does not change original and vice versa
>>> capital_copy = capital.copy()
>>> print(capital_copy)
{'India': 'Delhi', 'Germany': 'Berlin'}

#deleting an element
>>> del capital['India']

#Trying to delete a non existant element
>>> del capital['Bhutan']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'Bhutan'

No comments:

Post a Comment