Dictionary in Python

Dictionary in Python

Dictionary in Python

Dictionary in Python is collection of unordered items. Python provide in-built support for dictionary. Unlike, other in-built data structures in which they have single value such list, tuple and set. Python uses key value pair and separated by a colon i.e key:value, and value can be accessed by key. Keys are separated by a comma. The element of a dictionary are enclosed in curly braces.
It would be better to understand by using examples.
So, move to terminal or jupyter notebook.

Create a Dictionary in Python

In this example I will create a dictionary in which countries are keys and their capitals values.
>>>d={‘India’:’New Delhi’, ‘Germany’:’Berlin’, ‘France’:’Paris’, ‘Spain’:’Madrid’}
Dictionary in Python can also be created using dict() constructor function.
d=dict({‘India’:’New Delhi’, ‘Germany’:’Berlin’, ‘France’:’Paris’, ‘Spain’:’Madrid’})
Type of keys and values in dictionary can be integer, float and string types.
>>>e={5.0:’Five’,6:’Six’,’Seven’:7}

Accessing an Element(s) from Dictionary

Suppose you want to access capitals of countries from the dictionary d.
d={‘India’:’New Delhi’, ‘Germany’:’Berlin’, ‘France’:’Paris’, ‘Spain’:’Madrid’}
>>>print(d[‘Germany’])
Output:’Berlin’
>>>print(d[‘France’])
Output: Paris
Suppose you want to access values from the dictionary e.
>>>print(e[5.0])
Output:’Five’
>>>print(e[‘Seven’])
Output:7

Using get method
>>>value=e.get(6)
>>>print(value)
Output: 6

Adding an Element(s) to a Dictionary

If you want add an element in the dictionary e={5.0:’Five’,6:’Six’,’Seven’:7}.
The first method is
>>>e[‘8′]=’Eight’
>>>print(e)
Output: {5.0: ‘Five’, 6: ‘Six’, ‘Seven’: 7, 8: ‘Eight’}

The second method is to use update function
>>>e.update({9:’Nine’})
>>>print(e)
Output: {5.0: ‘Five’, 6: ‘Six’, ‘Seven’: 7, 8: ‘Eight’, 9: ‘Nine’}

Deleting an Element(s) from Dictionary

pop() function can be used to delete an element.
See example, delete key:value pair 6: ‘Six’.
>>>e.pop(6)
Output: {5.0: ‘Five’, ‘Seven’: 7, 8: ‘Eight’, 9: ‘Nine’}

Using del command to delete key:value pair 8: ‘Eight’ from dictionary e={5.0: ‘Five’, ‘Seven’: 7, 8: ‘Eight’, 9: ‘Nine’}
>>>del e[8]
>>>print(e)
Output: {5.0: ‘Five’, ‘Seven’: 7, 9: ‘Nine’}

Leave a Comment

Your email address will not be published. Required fields are marked *

©Postnetwork-All rights reserved.