Iterating through a dictionary

# Methods and attributes of dictionaries
dir({})
['__class__',
 '__class_getitem__',
 '__contains__',
 '__delattr__',
 '__delitem__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__ior__',
 '__iter__',
 '__le__',
 '__len__',
 '__lt__',
 '__ne__',
 '__new__',
 '__or__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__reversed__',
 '__ror__',
 '__setattr__',
 '__setitem__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 'clear',
 'copy',
 'fromkeys',
 'get',
 'items',
 'keys',
 'pop',
 'popitem',
 'setdefault',
 'update',
 'values']

iter in the above output means that the dictionary is iterable and we can use the for loop directly on a dictionary to iterate over the keys.

Iterating the keys of a dictionary

ipl_team_cities = {
    "Chennai Super Kings": "Chennai",
    "Delhi Capitals": "Delhi",
    "Kings XI Punjab": "Mohali",
    "Kolkata Knight Riders": "Kolkata",
    "Mumbai Indians": "Mumbai",
    "Rajasthan Royals": "Jaipur",
    "Royal Challengers Bangalore": "Bangalore",
    "Sunrisers Hyderabad": "Hyderabad"
}
for key in ipl_team_cities:
    print(key)
Chennai Super Kings
Delhi Capitals
Kings XI Punjab
Kolkata Knight Riders
Mumbai Indians
Rajasthan Royals
Royal Challengers Bangalore
Sunrisers Hyderabad

Iterating over keys and values

# items() is a method which will return a new 'view' of the dictionary items
# If the dictionary changes, the view will reflect the changes
ipl_team_cities.items()
dict_items([('Chennai Super Kings', 'Chennai'), ('Delhi Capitals', 'Delhi'), ('Kings XI Punjab', 'Mohali'), ('Kolkata Knight Riders', 'Kolkata'), ('Mumbai Indians', 'Mumbai'), ('Rajasthan Royals', 'Jaipur'), ('Royal Challengers Bangalore', 'Bangalore'), ('Sunrisers Hyderabad', 'Hyderabad')])
# views can be iterated over
for item in ipl_team_cities.items():
    print(item)
('Chennai Super Kings', 'Chennai')
('Delhi Capitals', 'Delhi')
('Kings XI Punjab', 'Mohali')
('Kolkata Knight Riders', 'Kolkata')
('Mumbai Indians', 'Mumbai')
('Rajasthan Royals', 'Jaipur')
('Royal Challengers Bangalore', 'Bangalore')
('Sunrisers Hyderabad', 'Hyderabad')
# Unpacking the tuple
for key, value in ipl_team_cities.items():
    print(key, '-', value)
Chennai Super Kings - Chennai
Delhi Capitals - Delhi
Kings XI Punjab - Mohali
Kolkata Knight Riders - Kolkata
Mumbai Indians - Mumbai
Rajasthan Royals - Jaipur
Royal Challengers Bangalore - Bangalore
Sunrisers Hyderabad - Hyderabad

Dictionary Comprehensions

teams = list(ipl_team_cities.keys())
cities = list(ipl_team_cities.values())
teams
['Chennai Super Kings',
 'Delhi Capitals',
 'Kings XI Punjab',
 'Kolkata Knight Riders',
 'Mumbai Indians',
 'Rajasthan Royals',
 'Royal Challengers Bangalore',
 'Sunrisers Hyderabad']
new_dict = {key:value for key, value in zip(teams, cities)}
new_dict
{'Chennai Super Kings': 'Chennai',
 'Delhi Capitals': 'Delhi',
 'Kings XI Punjab': 'Mohali',
 'Kolkata Knight Riders': 'Kolkata',
 'Mumbai Indians': 'Mumbai',
 'Rajasthan Royals': 'Jaipur',
 'Royal Challengers Bangalore': 'Bangalore',
 'Sunrisers Hyderabad': 'Hyderabad'}
# Dictionary comprehension using items() method
# swapping the keys and values
new_dict_2 = {value:key for key, value in ipl_team_cities.items()}
new_dict_2
{'Chennai': 'Chennai Super Kings',
 'Delhi': 'Delhi Capitals',
 'Mohali': 'Kings XI Punjab',
 'Kolkata': 'Kolkata Knight Riders',
 'Mumbai': 'Mumbai Indians',
 'Jaipur': 'Rajasthan Royals',
 'Bangalore': 'Royal Challengers Bangalore',
 'Hyderabad': 'Sunrisers Hyderabad'}

Filtering using dictionary comprehension

new_dict_3 = {key:value for key, value in ipl_team_cities.items() if value in ['Chennai', 'Delhi']}
new_dict_3
{'Chennai Super Kings': 'Chennai', 'Delhi Capitals': 'Delhi'}

Sorting the dictionary

ipl_sorted = {key:ipl_team_cities[key] for key in sorted(ipl_team_cities)}
ipl_sorted
{'Chennai Super Kings': 'Chennai',
 'Delhi Capitals': 'Delhi',
 'Kings XI Punjab': 'Mohali',
 'Kolkata Knight Riders': 'Kolkata',
 'Mumbai Indians': 'Mumbai',
 'Rajasthan Royals': 'Jaipur',
 'Royal Challengers Bangalore': 'Bangalore',
 'Sunrisers Hyderabad': 'Hyderabad'}
# Sorting by values
incomes = {'apple': 5600.00, 'orange': 3500.00, 'banana': 5000.00}
def by_value(item):
    return item[1]

for k, v in sorted(incomes.items(), key=by_value):
    print(k, '->', v)
orange -> 3500.0
banana -> 5000.0
apple -> 5600.0

In the above example, by_value is a key function. It is telling sorted() to sort incomes.items() by the second element of each item, i.e by the value item[1]

Using map() for iteration

  • Python map() takes a function and an iterable as arguments.
  • map() returns a map object whose values are the return values of calling the function on each item of the iterable.
product_prices = {
    'Product 1': 10.99,
    'Product 2': 5.99,
    'Product 3': 8.49,
    'Product 4': 12.99,
    'Product 5': 15.99,
    'Product 6': 7.99,
    'Product 7': 6.49,
    'Product 8': 9.99,
    'Product 9': 3.99,
    'Product 10': 11.49
}
def discount(price):
    return (price[0],round(price[1]*0.9,2))

new_product_prices = dict(map(discount, product_prices.items()))  
new_product_prices
{'Product 1': 9.89,
 'Product 2': 5.39,
 'Product 3': 7.64,
 'Product 4': 11.69,
 'Product 5': 14.39,
 'Product 6': 7.19,
 'Product 7': 5.84,
 'Product 8': 8.99,
 'Product 9': 3.59,
 'Product 10': 10.34}

using filter() on dictionaries

  • filter() takes a function and iterable as arguments
  • It returns an iterator from those elements of iterable for which function returns True
def low_price(price):
    return new_product_prices[price] < 6.0

low_prices = list(filter(low_price, new_product_prices))
low_prices
['Product 2', 'Product 7', 'Product 9']

Using ChainMap for Iteration

  • ChainMap is a dictionary that allows you to combine multiple dictionaries into one.
  • It creates a single view of multiple mappings
from collections import ChainMap
fruit_prices = {'pear': 0.35, 'mango':0.45}
veg_prices = {'potato': 0.20, 'tomato': 0.25}
chained_dict = ChainMap(fruit_prices, veg_prices)
chained_dict
ChainMap({'pear': 0.35, 'mango': 0.45}, {'potato': 0.2, 'tomato': 0.25})
for key in chained_dict:
    print(key, '->', chained_dict[key])
potato -> 0.2
tomato -> 0.25
pear -> 0.35
mango -> 0.45

Using chain from itertools

  • chain() is similar to ChainMap(). we can combine multiple dictionaries and iterate over them
from itertools import chain
for item in chain(fruit_prices.items(), veg_prices.items()):
    print(item)
('pear', 0.35)
('mango', 0.45)
('potato', 0.2)
('tomato', 0.25)

Iterating using unpacking operator

# using unpacking operator to create single dictionary from multiple dictionaries
{**veg_prices, **fruit_prices}
{'potato': 0.2, 'tomato': 0.25, 'pear': 0.35, 'mango': 0.45}
for k, v in {**veg_prices, **fruit_prices}.items():
    print(k, '->', v)
potato -> 0.2
tomato -> 0.25
pear -> 0.35
mango -> 0.45