Dictionary (dict) methods in Python

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

This code defines a dictionary named “myDict” with three key-value pairs.

The first part of the code uses a for loop to iterate over the items in the dictionary and prints the key-value pairs. The items() method returns a view of the dictionary’s items, which can be iterated over using a for loop.

The next part of the code demonstrates some of the built-in methods of dictionaries:

  • clear() method removes all items from the dictionary.
  • copy() method creates a shallow copy of the dictionary and returns the new dictionary.
  • items() method returns a set-like object providing a view on the dictionary’s items.
  • keys() method returns a set-like object providing a view on the dictionary’s keys.
  • values() method returns an object providing a view on the dictionary’s values.
  • get() method returns the value for a key if it exists in the dictionary, otherwise it returns the value specified as the second argument to the method. If the second argument is not specified and the key is not in the dictionary, get() returns None.
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