14.8 Dictionary Methods

By | October 4, 2021

Dictionary Methods

Example:

Create a dictionary with 3 keys, all with the value 0:
x = (‘key1’, ‘key2’, ‘key3’)
y = 0
thisdict = dict.fromkeys(x, y)
print(thisdict)

Output:
[‘key1’: 0, ‘key2’: 0, ‘key3’: 0]

Python has a set of built-in methods that you can use on dictionaries.

MethodSyntaxDescription
clear()dictionary.clear()Removes all the elements from the dictionary
copy()dictionary.copy()Returns a copy of the dictionary
fromkeys()dict.fromkeys(keys, value)Returns a dictionary with the specified keys and value
get()dictionary.get(keyname, value)Returns the value of the specified key
items()dictionary.items()Returns a list containing a tuple for each key value pair
keys()dictionary.keys()Returns a list containing the dictionary’s keys
pop()dictionary.pop(keyname, defaultvalue)Removes the element with the specified key
popitem()dictionary.popitem()Removes the last inserted key-value pair
setdefault()dictionary.setdefault(keyname, value)Returns the value of the specified key. If the key does not exist: insert the key, with the specified value
update()dictionary.update(iterable)Updates the dictionary with the specified key-value pairs
values()dictionary.values()Returns a list of all the values in the dictionary

Leave a Reply

Your email address will not be published. Required fields are marked *