With dictionaries an assignment between object pairs is established. A dictionary can contain any number of key/value pairs. In contrast to the lists, the keys do not necessarily have to be integers, but can also represent arbitrary objects.
Line | Description |
---|---|
1 | Creates a dictionary called myDict and initializes it with the key / value pairs: “prename”: “Mike”, “name”: “Miller” and “age”: 25 |
4 – 5 | Iterating over dictionaries using for loop to print key / value pairs |
8 | The clear() method removes all items from dictionary |
11 | The copy() method creates a shallow copy of dictionary |
14 | The items() method creates a set-like object providing a view on dictionary’s items |
17 | The keys() method creates a set-like object providing a view on dictionary’s keys |
20 | The values() method providing a view on dictionary’s values |
23 | The get() method returns the value for key a if it exists, otherwise b |
myDict = {"prename": "Mike", "name": "Miller", "age": 25}
# Iterating over dictionaries using 'for' loop
for key, value in myDict.items():
print(key, value)
# D.clear() -> None. Remove all items from D.
a = myDict.clear()
# D.copy() -> a shallow copy of D
b = myDict.copy()
# D.items() -> a set-like object providing a view on D's items
c = myDict.items()
# D.keys() -> a set-like object providing a view on D's keys
d = myDict.keys()
# D.values() -> an object providing a view on D's values
e = myDict.values()
# returns the value for key a if it exists, otherwise b
f = myDict.get(a, b)
prename Mike
name Miller
age 25