Page 373 - Computer Science Class 11 With Functions
P. 373
Here is an example of a nested dictionary:
>>> myDict = {
... 'person1': {'name': 'Alice', 'age': 25, 'gender': 'female'},
... 'person2': {'name': 'Bob', 'age': 30, 'gender': 'male'}
... }
In this example, myDict is a dictionary that contains two keys, 'person1' and 'person2'. The value for each of
these keys is another dictionary, which contains information about each person.
To access a value in a nested dictionary, we can use multiple square brackets to drill down to the desired level. For
example, to access the name of person1 in the above example, you can do:
>>> name = myDict['person1']['name']
>>> print(name)
'Alice'
In this example, myDict['person1'] returns the inner dictionary for 'person1', and myDict['person1']
['name'] returns the value associated with the 'name' key in that inner dictionary.
14.4 Traversing a Dictionary
We can traverse or iterate over the keys, values, or items of a dictionary using a for loop.
Here are three different ways to traverse a dictionary in Python:
1. Traverse the keys of a dictionary:
01 my_dict = {'apple': 3, 'banana': 2, 'orange': 1}
02 for key in my_dict:
03 print(key)
Sample output:
apple
banana
orange
2. Traverse the values of a dictionary:
01 my_dict = {'apple': 3, 'banana': 2, 'orange': 1}
02 for value in my_dict.values():
03 print(value)
Sample output:
3
2
1
3. Traverse both the keys and values of a dictionary:
01 my_dict = {'apple': 3, 'banana': 2, 'orange': 1}
02 for key, value in my_dict.items():
03 print(key, value)
Sample output:
apple 3
banana 2
orange 1
In each of the above examples, we use a for loop to iterate over the keys, values, or items of the dictionary. The
for loop assigns each key, value, or key-value pair to a variable (depending on which method we're using) during
each iteration, and the loop body then executes some code using that variable. Note that the order in which the
keys, values, or items are traversed is not guaranteed to be the same as the order in which they were added to the
dictionary.
Dictionaries 371

