Dictionary Methods

Dicitonary methods are like any other methods. They are built-ins that affect only dictionaries.

dict.keys(), dict.values(), dict.items()

The method keys() returns all keys in the dictionary. The method values() returns all the values. The method items() returns a tuple of the (key,value) pair. These methods make it very easy to loop through all keys and find a specific key, for example, and get the value of that key.

Here we add a nested dictionary and use the same methods as we did before. You will notice that the keys() do no show the nested keys. You will need to use a loop to go into the nested dictionary to get the ame results with the nested one. However the values() method will have a value as the nested dictionary. The items() will show tuple form.

dict.get()

Trying to call a dicitonary key that does not exist will raise a KeyError. You can either use a try/except to catch the error or you can use the get() method. The get method will 'get' the value of the key and if it does not exist, will return the value None.

By default, the get() method will return None. You can change the value that it returns with a second argument if no key is found. The 101 has returned due to the key d['tester'] not existing.

dict.update()

The update() method can be used to add new key:value pairs to the dictionary. If the key already exists, the value will be 'updated' to the new value.

dict.pop()

The pop() method will do the same as it did with lists, except it takes a key instead of a position. It will delete the key and return the value it had.

dict.fromkeys()

Provided you want all the same values for each key, you can use the fromkeys() method to create a dictionary with keys all the same. Hover a for loop would do the same and be more productive and adaptable.

dict.clear()

The method clear() will completely wipe out the dictionary.