Dictionary (dict) methods

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.

Code Explanation

LineDescription
1Creates a dictionary called myDict and initializes it with the key / value pairs: “prename”: “Mike”, “name”: “Miller” and “age”: 25
4 – 5Iterating over dictionaries using for loop to print key / value pairs
8The clear() method removes all items from dictionary
11The copy() method creates a shallow copy of dictionary
14The items() method creates a set-like object providing a view on dictionary’s items
17The keys() method creates a set-like object providing a view on dictionary’s keys
20The values() method providing a view on dictionary’s values
23The 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)
Output
prename Mike
name Miller
age 25