Skip to content

Dictionary Methods

diagram four ways to read a key, and what each does when it is missing mermaid
The difference is not style -- it is what happens when the key is absent, and whether the dictionary is changed as a side effect. Two of these raise, one returns a default without touching the dictionary, and one inserts.

In Python, a dictionary is a collection of key-value pairs. Each key is connected to a value, and you can use a key to access the value associated with that key. A key’s value can be a number, a string, a list, or even another dictionary. In fact, you can use any object that you can create in Python as a value in a dictionary. We have a set of methods that can be used with dictionaries. We will cover the following methods - clear, copy, fromkeys, get, items, keys, pop, popitem, setdefault, update, and values.

S.No.MethodDescriptionExample
1clear()Removes all the elements from the dictionarymy_dict.clear()
2copy()Returns a copy of the dictionarymy_dict.copy()
3fromkeys()Returns a dictionary with the specified keys and valuemy_dict.fromkeys(keys, value)
4get()Returns the value of the specified keymy_dict.get(key)
5items()Returns a list containing a tuple for each key value pairmy_dict.items()
6keys()Returns a list containing the dictionary’s keysmy_dict.keys()
7pop()Removes the element with the specified keymy_dict.pop(key)
8popitem()Removes the last inserted key-value pairmy_dict.popitem()
9setdefault()Returns the value of the specified key. If the key does not exist: insert the key, with the specified valuemy_dict.setdefault(key, value)
10update()Updates the dictionary with the specified key-value pairsmy_dict.update(key, value)
11values()Returns a list of all the values in the dictionarymy_dict.values()
12has_key()Returns True if a key exists in the dictionarymy_dict.has_key(key)
13len()Returns the number of items in the dictionarylen(my_dict)
14delRemoves the item with the specified keydel my_dict[key]
15inReturns True if a key exists in the dictionarykey in my_dict
16not inReturns True if a key does not exist in the dictionarykey not in my_dict

The clear() method removes all the elements from a dictionary.

clear.py
data = {'a': 1, 'b': 2, 'c': 3}
data.clear()
print(data)

Output:

command
C:\Users\username>python clear.py
{}

In this example, we declare a dictionary and assign it to the variable data. We then use the clear() method to remove all the elements from the dictionary. The output shows that the dictionary is empty.

The copy() method returns a copy of the specified dictionary.

copy.py
data = {'a': 1, 'b': 2, 'c': 3}
new_data = data.copy()
print(new_data)

Output:

command
C:\Users\username>python copy.py
{'a': 1, 'b': 2, 'c': 3}

In this example, we declare a dictionary and assign it to the variable data. We then use the copy() method to create a copy of the dictionary and assign it to the variable new_data. The output shows that the dictionary is copied.

The fromkeys() method returns a dictionary with the specified keys and value.

fromkeys.py
keys = ('a', 'b', 'c')
value = 0
data = dict.fromkeys(keys, value)
print(data)

Output:

command
C:\Users\username>python fromkeys.py
{'a': 0, 'b': 0, 'c': 0}

In this example, we declare a tuple and assign it to the variable keys. We then declare a variable value and assign it the value 0. We then use the fromkeys() method to create a dictionary with the specified keys and value and assign it to the variable data. The output shows that the dictionary is created.

The get() method returns the value of the specified key.

get.py
data = {'a': 1, 'b': 2, 'c': 3}
value = data.get('a')
print(value)

Output:

command
C:\Users\username>python get.py
1

In this example, we declare a dictionary and assign it to the variable data. We then use the get() method to get the value of the key a and assign it to the variable value. The output shows that the value is returned.

The items() method returns a list containing a tuple for each key value pair.

items.py
data = {'a': 1, 'b': 2, 'c': 3}
items = data.items()
print(items)

Output:

command
C:\Users\username>python items.py
dict_items([('a', 1), ('b', 2), ('c', 3)])

In this example, we declare a dictionary and assign it to the variable data. We then use the items() method to get the items of the dictionary and assign it to the variable items. The output shows that the items are returned.

The keys() method returns a list containing the dictionary’s keys.

keys.py
data = {'a': 1, 'b': 2, 'c': 3}
keys = data.keys()
print(keys)

Output:

command
C:\Users\username>python keys.py
dict_keys(['a', 'b', 'c'])

In this example, we declare a dictionary and assign it to the variable data. We then use the keys() method to get the keys of the dictionary and assign it to the variable keys. The output shows that the keys are returned.

The pop() method removes the element with the specified key.

pop.py
data = {'a': 1, 'b': 2, 'c': 3}
data.pop('a')
print(data)

Output:

command
C:\Users\username>python pop.py
{'b': 2, 'c': 3}

In this example, we declare a dictionary and assign it to the variable data. We then use the pop() method to remove the element with the key a. The output shows that the element is removed.

The popitem() method removes the last inserted key-value pair.

popitem.py
data = {'a': 1, 'b': 2, 'c': 3}
data.popitem()
print(data)

Output:

command
C:\Users\username>python popitem.py
{'a': 1, 'b': 2}

In this example, we declare a dictionary and assign it to the variable data. We then use the popitem() method to remove the last inserted key-value pair. The output shows that the key-value pair is removed.

The setdefault() method returns the value of the specified key. If the key does not exist: insert the key, with the specified value.

setdefault.py
data = {'a': 1, 'b': 2, 'c': 3}
value = data.setdefault('a', 0)
print(value)
value = data.setdefault('d', 4)
print(value)
print(data)

Output:

command
C:\Users\username>python setdefault.py
1
4
{'a': 1, 'b': 2, 'c': 3, 'd': 4}

In this example, we declare a dictionary and assign it to the variable data. We then use the setdefault() method to get the value of the key a and assign it to the variable value. The output shows that the value is returned. We then use the setdefault() method to get the value of the key d and assign it to the variable value. The output shows that the value is returned and the key-value pair is added to the dictionary.

The update() method updates the dictionary with the specified key-value pairs.

update.py
data = {'a': 1, 'b': 2, 'c': 3}
data.update({'d': 4, 'e': 5})
print(data)

Output:

command
C:\Users\username>python update.py
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

In this example, we declare a dictionary and assign it to the variable data. We then use the update() method to update the dictionary with the specified key-value pairs. The output shows that the dictionary is updated.

The values() method returns a list of all the values in the dictionary.

values.py
data = {'a': 1, 'b': 2, 'c': 3}
values = data.values()
print(values)

Output:

command
C:\Users\username>python values.py
dict_values([1, 2, 3])

In this example, we declare a dictionary and assign it to the variable data. We then use the values() method to get the values of the dictionary and assign it to the variable values. The output shows that the values are returned.

The has_key() method returns True if a key exists in the dictionary.

has_key.py
data = {'a': 1, 'b': 2, 'c': 3}
print(data.has_key('a'))
print(data.has_key('d'))

Output:

command
C:\Users\username>python has_key.py
True
False

In this example, we declare a dictionary and assign it to the variable data. We then use the has_key() method to check if the key a exists in the dictionary. The output shows that the key exists. We then use the has_key() method to check if the key d exists in the dictionary. The output shows that the key does not exist.

The len() method returns the number of items in the dictionary.

len.py
data = {'a': 1, 'b': 2, 'c': 3}
print(len(data))

Output:

command
C:\Users\username>python len.py
3

In this example, we declare a dictionary and assign it to the variable data. We then use the len() method to get the number of items in the dictionary. The output shows that the number of items is returned.

The del keyword removes the item with the specified key.

del.py
data = {'a': 1, 'b': 2, 'c': 3}
del data['a']
print(data)

Output:

command
C:\Users\username>python del.py
{'b': 2, 'c': 3}

In this example, we declare a dictionary and assign it to the variable data. We then use the del keyword to remove the item with the key a. The output shows that the item is removed.

The in keyword returns True if a key exists in the dictionary.

in.py
data = {'a': 1, 'b': 2, 'c': 3}
print('a' in data)
print('d' in data)

Output:

command
C:\Users\username>python in.py
True
False

In this example, we declare a dictionary and assign it to the variable data. We then use the in keyword to check if the key a exists in the dictionary. The output shows that the key exists. We then use the in keyword to check if the key d exists in the dictionary. The output shows that the key does not exist.

The not in keyword returns True if a key does not exist in the dictionary.

not_in.py
data = {'a': 1, 'b': 2, 'c': 3}
print('a' not in data)
print('d' not in data)

Output:

command
C:\Users\username>python not_in.py
False
True

In this example, we declare a dictionary and assign it to the variable data. We then use the not in keyword to check if the key a does not exist in the dictionary. The output shows that the key exists. We then use the not in keyword to check if the key d does not exist in the dictionary. The output shows that the key does not exist.

In this tutorial, we have covered the methods available for dictionaries in Python. We have covered the following methods - clear, copy, fromkeys, get, items, keys, pop, popitem, setdefault, update, and values. For more information on dictionaries, you can refer to the official documentation. For more tutorials on Python, you can refer to the Python Central Hub.


sketch Four ways to read a key, and what each does when it is missing p5.js
The same lookup, four spellings. They differ in whether they raise, whether they return a default, and whether they change the dictionary as a side effect. Watch the dictionary panel: only one of the four inserts, and that one is the reason a grouping loop can quietly grow keys you never meant to add.
pch.quizTag pch.quizDefaultTitle
  1. `d = {'a': 1}`. What does `d.setdefault('zz', [])` return, and what is `d` afterwards?

    pch.quizShowAnswer

    C — `[]`, and `d` now has a `'zz'` key — `setdefault` is the only one of the four readers that INSERTS. That is useful for grouping and surprising when you meant a read-only lookup.

  2. `e = {'k': 1}`. Does `e.setdefault('k', make())` call `make()`?

    pch.quizShowAnswer

    B — Yes — arguments are evaluated before the call — Verified: `make()` ran. That is why `d.setdefault(k, []).append(x)` allocates a throwaway list every iteration, and why `defaultdict(list)` is the better tool for grouping.

  3. What does `d.get('missing')` return?

    pch.quizShowAnswer

    B — `None` — `get` returns `None` for an absent key rather than raising, so a typo in the key name looks exactly like a genuinely missing value.

  4. You take `ks = d.keys()`, then add a key to `d`. What does `list(ks)` show?

    pch.quizShowAnswer

    B — The new key as well — a view is live — Verified. Views are windows onto the dictionary. Related: mutating a dict while iterating it raises `RuntimeError: dictionary changed size during iteration` — iterate over `list(d)` if you plan to modify.

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading