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.

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’}
Output: Paris
Suppose you want to access values from the dictionary e.

Using get method
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
Output: {5.0: ‘Five’, 6: ‘Six’, ‘Seven’: 7, 8: ‘Eight’}

The second method is to use update function
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’.
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’}

Share to Your Friend

Be the first to comment on "Dictionary in Python"

Leave a comment

Your email address will not be published.