Modue 3 - Dictionaries
Modue 3 - Dictionaries
21CSE23
DICTIONARIES
Dictionaries
Values
Keys
Creating an empty dictionary using
dict()
Note: The order of key – value pair will differ from the
order in which these were created
Dictionaries vs. Lists
False
The get() Method
After:
Program to count the number of
occurrences of each letter in a
string without function.
Output:
Pretty
Printing
print(sum(d.values()))
OUTPUT:
60
Using Data Structures to Model
Real-World Things
1. Chess Board.
2. A Tic-Tac-Toe Board.
Nested dictionaries
• A dictionary inside a dictionary
Output
Accessing a nested dictionary
Output
• Program-2
• allGuests = {'Alice': {'apples': 5, 'pretzels': 12}, 'Bob': {'ham
sandwiches': 3, 'apples': 2}, 'Carol': {'cups': 3, 'apple pies': 1}}
• def totalBrought(guests, item):
numBrought = 0
for k, v in guests.items():
numBrought = numBrought + v.get(item, 0)
return numBrought
• print('Number of things being brought:’)
• print(' - Apples ' + str(totalBrought(allGuests, 'apples')))
• print(' - Cups ' + str(totalBrought(allGuests, 'cups')))
• print(' - Cakes ' + str(totalBrought(allGuests, 'cakes')))
• print(' - Ham Sandwiches ' + str(totalBrought(allGuests, 'ham
sandwiches')))
• print(' - Apple Pies ' + str(totalBrought(allGuests, 'apple pies’)))
• print(' - pretzels ' + str(totalBrought(allGuests, 'pretzels')))
• OUTPUT:
Number of things being brought:
- Apples 7
- Cups 3
- Cakes 0
- Ham Sandwiches 3
- Apple Pies 1
- pretzels 12