Python

Dictionary in Python

A dictionary is an un-ordered data structure, its elements are stored as a key:value pair.
Key must be unique and immutable
If key is not unique, last value of key will override previous values

# Create an empty dictionary
country ={}
Another way to create an empty dictionary
country=dict()


# Create a dictionary with elements
Lets create a dictionary as country with country name as key and capital as its value
country = {'India': 'New Delhi', 'Australia': 'Canberra'}
print(country)
{'India': 'New Delhi', 'Australia': 'Canberra'}


# Add an element in Dictionary
Dictionary is mutable. We can add new items or change the value of existing items.
If the key is already present, value gets updated, else a new key: value pair is added to the dictionary.
country['China']='Beijing';
print(country);

{'India': 'New Delhi', 'Australia': 'Canberra', 'China': 'Beijing'}

Access elements from a dictionary
Syntax: dictionary[key]
print(country['China'])

Beijing

Nested dictionary: value in dictionary , can be a dictionary itself
country={'India': {'Capital':'New Delhi', 'Currency':'Indian Rupee', 'language':['Hindi','English']},
'China':{'Capital':'Beijing', 'Currency':'Chinese Yuan','language':['Mandarin']}}

Syntax : dict.keys() : to retrieve all keys of a dictionary
Syntax : dict.values() : to retrieve all values of a dictionary

for k in country.keys():
print("{}:".format(k))
for v in country[k].values():
print("\t{}".format(v))


India:
New Delhi
Indian Rupee
['Hindi', 'English']
China:
Beijing
Chinese Yuan
['Mandarin']


Syntax: dict.items() : to retrieve key and its values
for k in country.keys():
print(k)
for k1,v1 in country[k].items():
print("\t{}: {}".format(k1,v1))


India
Capital: New Delhi
Currency: Indian Rupee
language: ['Hindi', 'English']
China
Capital: Beijing
Currency: Chinese Yuan
language: ['Mandarin']


Access an individual element in a nested dictionary
To retrieve language spoken in China
country.get('China').get('language')
['Mandarin']


To remove an element from dictionary
del country['China'];
print(country)
{'India': {'Capital': 'New Delhi', 'Currency': 'Indian Rupee', 'language': ['Hindi', 'English']}}

Adding one more element to dictionary country
country['France']={'Capital':'Paris', 'Currency':'Euro', 'language':['French']}

print(country)
{'India': {'Capital': 'New Delhi', 'Currency': 'Indian Rupee', 'language': ['Hindi', 'English']}, 'France': {'Capital': 'Paris', 'Currency': 'Euro', 'language': ['French']}}

To display dictionary elements in sorted order
for k1 in sorted(country):
print(k1)
for k2 in sorted(country[k1]):
print("\t{}:{}".format(k2, country[k1][k2]))

France
Capital:Paris
Currency:Euro
language:['French']
India
Capital:New Delhi
Currency:Indian Rupee
language:['Hindi', 'English']

Shekhar Pandey

Add comment

Follow us

Don't be shy, get in touch. We love meeting interesting people and making new friends.