Page 214 - Information_Practice_Fliipbook_Class11
P. 214
Note that the variables myDict and myDictCopy refer to two different objects having the ids 2386829086208
and 2386829094976, respectively.
● myDict.fromkeys(<keys>, <value>): The method fromkeys() returns a dictionary with the specified
keys and the specified value. Interestingly, the method does not update the existing dictionary myDict.
Example:
>>> subjects = {}
>>> subjectTitle = {'Physics', 'Mathematics', 'Computer Sc.'}
>>> marks = 0
>>> subjects.fromkeys(subjectTitle, marks)
{'Computer Sc.': 0, 'Mathematics': 0, 'Physics': 0}
>>> subjects
{}
● myDict.setdefault(key, [value]): setdefault() method returns the value of the item with
the specified key. However, if the key does not exist, then the key is inserted in the dictionary, and the key is
associated with the value passed as the second parameter.
Example:
>>> myDict = { 'b':'beta', 'g':'gamma', 'a':'alpha' }
>>> myDict.setdefault('a')
'alpha'
>>> myDict.setdefault('a', 'aa')
'alpha'
>>> myDict
{'b': 'beta', 'g': 'gamma', 'a': 'alpha'}
>>> myDict.setdefault('d','delta')
'delta'
>>> myDict
{'b': 'beta', 'g': 'gamma', 'a': 'alpha', 'd': 'delta'}
8.5 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)
200 Touchpad Informatics Practices-XI

