Dictionary

Python tutorial for Dictionaries

A dictionary is an example of a key value store. It allows you to store and retrieve elements by referencing a key. As dictionaries are referenced by key, they have very fast lookup.

Key : The desired key to lookup, Value : The value to set or return.

Creating a Dictionary

d = {'key': 'value'}
print(d)

#Output
{'key': 'value'}
# To create a dictionary and populating it with values
stock = {'eggs': 5, 'milk': 10, 'bread': 5}
print(stock)

#Output
{'eggs': 5, 'milk': 10, 'bread': 5}
# To create an empty dictionary
stock = {}
# and populating it after
stock['eggs'] = 5
stock['milk'] = 10
stock['bread'] = 7

#Output
{'eggs': 5, 'milk': 10, 'bread': 7}

Accessing values of dictionary

# To access by elements
print(stock['milk'])
print(stock['bread'])

#Output
10
7

# To access by keys
print(stock.keys())

#Output
dict_keys(['eggs', 'milk', 'bread'])

# To access by values
print(stock.values())

#Output
dict_values([5, 10, 7])

Merging Dictionaries

To merge dictionaries update() function is used-

# Merging Dictionaries
shop = {'stock': 100, 'staff': 2}
market = {'shops': 100, 'employees': 200}
marketshop = {}
marketshop.update(shop)
marketshop.update(market)
print(marketshop)

#Output
{'stock': 100, 'staff': 2, 'shops': 100, 'employees': 200}

Iterating over a Dictionary

for i in marketshop:
   print(i)

#Output
stock
staff
shops
employees
#By default loop works in keys of a dictionary.

To use loop in both keys and values-

for i in marketshop:
    print(i, marketshop[i])

#Output
stock 100
staff 2
shops 100
employees 200

Previous||Next Chapter

Leave a Reply