Here’s a look at some common methods that apply to Python dictionaries, and finally we’ll see a demo for all of these:
dict_2 all represent some kind of arbitrary dictionaries.
As the name suggests, it returns the length of key-value pairs in the dictionary.
It allows us to check whether the key is in the dictionary or not
key in dict
We can use this to avoid a key that is not in the dictionary. For example, using
dict[key] raise a
KeyError If the key is not in the dictionary, but using the following line of code does not prevent the python shortcut from evaluating it
and opinion if
key in dict returns false.
key in dict and dict[key]
It gets the value associated with the given key. It also accepts an optional default argument that is returned if the key is not in the dictionary. Even if the key is not present and the default value is not passed, the function returns None.
It returns dictionary keys
set of values:
It returns dictionary values
It returns dictionary items as a series of key-value rows.
Note: Using a loop with a dictionary returns a key with each iteration, i.e.
for key in dict iterates through a list of keys within the dictionary
It removes the last key-value pair from the dictionary and returns it.
It deletes the key-value pair associated with the given key. It also accepts an optional default argument that is returned if the key is not in the dictionary. Even if the key does not exist and the default value is not passed, the function raises a
As the name suggests, it clears the dictionary (clears it)
It combines the dictionary with another dictionary or iterative key-value pairs, as we saw in the dictionary definition. All key value pairs from both dictionaries are added to the first dictionary. If the key is already in the first dictionary, its value is updated using the value associated with the key in the second dictionary. If the key is not in the first dictionary
dict_1.update(dict_2) (Note: Only
dict_1 has been updated)