Which method would you use to return the value associated with a specified key and remove that key

Python dictionary is an ordered collection (starting from Python 3.7) of items. Each item of a dictionary has a key/value pair.

Dictionaries are optimized to retrieve values when the key is known.

Creating Python Dictionary

Creating a dictionary is as simple as placing items inside curly braces {} separated by commas.

An item has a key and a corresponding value that is expressed as a pair (key: value).

While the values can be of any data type and can repeat, keys must be of immutable type (string, number or tuple with immutable elements) and must be unique.

# empty dictionary my_dict = {} # dictionary with integer keys my_dict = {1: 'apple', 2: 'ball'} # dictionary with mixed keys my_dict = {'name': 'John', 1: [2, 4, 3]} # using dict() my_dict = dict({1:'apple', 2:'ball'}) # from sequence having each item as a pair my_dict = dict([(1,'apple'), (2,'ball')])

As you can see from above, we can also create a dictionary using the built-in dict() function.

Accessing Elements from Dictionary

While indexing is used with other data types to access values, a dictionary uses keys. Keys can be used either inside square brackets [] or with the get() method.

If we use the square brackets [], KeyError is raised in case a key is not found in the dictionary. On the other hand, the get() method returns None if the key is not found.

# get vs [] for retrieving elements my_dict = {'name': 'Jack', 'age': 26} # Output: Jack print(my_dict['name']) # Output: 26 print(my_dict.get('age')) # Trying to access keys which doesn't exist throws error # Output None print(my_dict.get('address')) # KeyError print(my_dict['address'])

Output

Jack 26 None Traceback (most recent call last): File "<string>", line 15, in <module> print(my_dict['address']) KeyError: 'address'

Changing and Adding Dictionary elements

Dictionaries are mutable. We can add new items or change the value of existing items using an assignment operator.

If the key is already present, then the existing value gets updated. In case the key is not present, a new (key: value) pair is added to the dictionary.

# Changing and adding Dictionary Elements my_dict = {'name': 'Jack', 'age': 26} # update value my_dict['age'] = 27 #Output: {'age': 27, 'name': 'Jack'} print(my_dict) # add item my_dict['address'] = 'Downtown' # Output: {'address': 'Downtown', 'age': 27, 'name': 'Jack'} print(my_dict)

Output

{'name': 'Jack', 'age': 27} {'name': 'Jack', 'age': 27, 'address': 'Downtown'}

Removing elements from Dictionary

We can remove a particular item in a dictionary by using the pop() method. This method removes an item with the provided key and returns the value.

The popitem() method can be used to remove and return an arbitrary (key, value) item pair from the dictionary. All the items can be removed at once, using the clear() method.

We can also use the del keyword to remove individual items or the entire dictionary itself.

# Removing elements from a dictionary # create a dictionary squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25} # remove a particular item, returns its value # Output: 16 print(squares.pop(4)) # Output: {1: 1, 2: 4, 3: 9, 5: 25} print(squares) # remove an arbitrary item, return (key,value) # Output: (5, 25) print(squares.popitem()) # Output: {1: 1, 2: 4, 3: 9} print(squares) # remove all items squares.clear() # Output: {} print(squares) # delete the dictionary itself del squares # Throws Error print(squares)

Output

16 {1: 1, 2: 4, 3: 9, 5: 25} (5, 25) {1: 1, 2: 4, 3: 9} {} Traceback (most recent call last): File "<string>", line 30, in <module> print(squares) NameError: name 'squares' is not defined

Python Dictionary Methods

Methods that are available with a dictionary are tabulated below. Some of them have already been used in the above examples.

Method Description
clear() Removes all items from the dictionary.
copy() Returns a shallow copy of the dictionary.
fromkeys(seq[, v]) Returns a new dictionary with keys from seq and value equal to v (defaults to None).
get(key[,d]) Returns the value of the key. If the key does not exist, returns d (defaults to None).
items() Return a new object of the dictionary's items in (key, value) format.
keys() Returns a new object of the dictionary's keys.
pop(key[,d]) Removes the item with the key and returns its value or d if key is not found. If d is not provided and the key is not found, it raises KeyError.
popitem() Removes and returns an arbitrary item (key, value). Raises KeyError if the dictionary is empty.
setdefault(key[,d]) Returns the corresponding value if the key is in the dictionary. If not, inserts the key with a value of d and returns d (defaults to None).
update([other]) Updates the dictionary with the key/value pairs from other, overwriting existing keys.
values() Returns a new object of the dictionary's values

Here are a few example use cases of these methods.

# Dictionary Methods marks = {}.fromkeys(['Math', 'English', 'Science'], 0) # Output: {'English': 0, 'Math': 0, 'Science': 0} print(marks) for item in marks.items(): print(item) # Output: ['English', 'Math', 'Science'] print(list(sorted(marks.keys())))

Output

{'Math': 0, 'English': 0, 'Science': 0} ('Math', 0) ('English', 0) ('Science', 0) ['English', 'Math', 'Science']

Python Dictionary Comprehension

Dictionary comprehension is an elegant and concise way to create a new dictionary from an iterable in Python.

Dictionary comprehension consists of an expression pair (key: value) followed by a for statement inside curly braces {}.

Here is an example to make a dictionary with each item being a pair of a number and its square.

# Dictionary Comprehension squares = {x: x*x for x in range(6)} print(squares)

Output

{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

This code is equivalent to

squares = {} for x in range(6): squares[x] = x*x print(squares)

Output

{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

A dictionary comprehension can optionally contain more for or if statements.

An optional if statement can filter out items to form the new dictionary.

Here are some examples to make a dictionary with only odd items.

# Dictionary Comprehension with if conditional odd_squares = {x: x*x for x in range(11) if x % 2 == 1} print(odd_squares)

Output

{1: 1, 3: 9, 5: 25, 7: 49, 9: 81}

To learn more dictionary comprehensions, visit Python Dictionary Comprehension.

Other Dictionary Operations

Dictionary Membership Test

We can test if a key is in a dictionary or not using the keyword in. Notice that the membership test is only for the keys and not for the values.

# Membership Test for Dictionary Keys squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81} # Output: True print(1 in squares) # Output: True print(2 not in squares) # membership tests for key only not value # Output: False print(49 in squares)

Output

True True False

Iterating Through a Dictionary

We can iterate through each key in a dictionary using a for loop.

# Iterating through a Dictionary squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81} for i in squares: print(squares[i])

Output

1 9 25 49 81

Dictionary Built-in Functions

Built-in functions like all(), any(), len(), cmp(), sorted(), etc. are commonly used with dictionaries to perform different tasks.

Function Description
all() Return True if all keys of the dictionary are True (or if the dictionary is empty).
any() Return True if any key of the dictionary is true. If the dictionary is empty, return False.
len() Return the length (the number of items) in the dictionary.
cmp() Compares items of two dictionaries. (Not available in Python 3)
sorted() Return a new sorted list of keys in the dictionary.

Here are some examples that use built-in functions to work with a dictionary.

# Dictionary Built-in Functions squares = {0: 0, 1: 1, 3: 9, 5: 25, 7: 49, 9: 81} # Output: False print(all(squares)) # Output: True print(any(squares)) # Output: 6 print(len(squares)) # Output: [0, 1, 3, 5, 7, 9] print(sorted(squares))

Output

False True 6 [0, 1, 3, 5, 7, 9]

The python dictionary has a set of in-built methods used to perform various tasks in the dictionary. Python dictionary is a collection of unordered elements. Elements in the dictionary are in the form of key-value pairs each key having its corresponding value.

Using some of the in-built dictionary methods such as items(), key(), values() we can access our desired key-value pairs. Using the get() method we can get a value for a specified key. If a key doesn’t exist in the dictionary it returns the default value None. Moreover, we can create a new dictionary from the given iterable objects using some Python Dictionary methods.

Furthermore, we can update, copy the dictionary using update() and copy() methods. On the other hand, we can delete all the key-value pairs using the clear() method. If you want to delete the element with the specified key, it is possible by using the pop() method of the Python dictionary.

Below are the most used dictionary method in Python, Click on each link from below table to understand with examples.

1. Dictionary Methods

MethodsDictionary Method Description
clear()Delete all the key: value pairs from the dictionary
copy()Returns a shallow copy of the dictionary
fromkeys()creates a new dictionary from the given iterable objects
get()Returns the value of the specified key
items()Returns a view object that allows a dynamic view of dictionary elements as a list of key, value (tuple) pairs.
keys()Returns a view object which contains a list of all keys related to the dictionary.
pop()Removes the element with the specified key
popitem()Removes the last inserted key-value pair
setdefault()It returns a value if the key is present. Otherwise, it inserts the key with the default value into the dictionary. The default value of the key is None.
update()Updates the dictionary with the specified key-value pairs
values()Returns a view object that contains a list of all the values stored in the dictionary.

2. Dictionary Methods Examples

2.1 clear()

clear() method is used to remove all elements from the python dictionary. When you have a dictionary with too many elements, deleting all elements of the dictionary one after another is a very time taken process, so use clear() method to delete all elements at once rather than deleting elements one by one. For example,

# Delete all key: value pairs from the dictionary technology = { 'course':'python', 'fee': 4000, 'duration': '60 days' } technology.clear() print("Technology:", technology) # Returns empty dictionary # Technology: {}

2.2 copy()

copy() method is used to get a copy of the python dictionary. You can copy the Python dictionary in different ways. copy() method does the shallow copy of the dictionary. For Example,

# Using copy() method copy the technology dictionary technology = { 'course':'python', 'fee': 4000, 'duration': '60 days' } new_technology=technology.copy() print("Original technology: ",technology) print("New technology: ",new_technology) # Output: # Original technology: {'course': 'python', 'fee': 4000, 'duration': '60 days'} # New technology: {'course': 'python', 'fee': 40000, 'duration': '60 days'}

2.3 fromkeys()

fromkeys() creates a new Python dictionary from the given iterable objects such as string, list, tuple, and set as keys and with a specified value. If no value is specified to value param, the values of keys are set to None by default. For example,

# Create a dictionary using fromkeys() technology ={"course","fee","duration"} dictionary=dict.fromkeys(technology ,'language') print(dictionary) # Output: # {'fee': 'language', 'course': 'language', 'duration': 'language'}

2.4 get()

get() method is used to get the value of the element with the specified keys from the Python dictionary. This method takes optional value param which is used to return the default value when a key is not present.

# Using get() method to get the value from dictionary technology={'course': 'python', 'fee': 4000} print('course:', technology.get('course')) # course: python print('fee:',technology.get('fee')) # fee: 4000

2.5 items()

items() method is used to return a view object of the python dictionary elements as tuples in a list. The items in the dictionary are unordered and mutable hence, they can be changed, removed, and added after the creation of the dictionary. However, the items cannot duplicate within the same dictionary.

# Using the items() to get dictionary elements technology = { 'course':'python', 'fee': 4000, 'duration': '60 days' } print(technology.items()) # Output: # dict_items([('course', 'python'), ('fee', 4000), ('duration', '60 days')])

2.6 keys()

Python dictionary keys() method is used to get the list of all the keys in the dictionary. The keys() method returns a view object which contains a list of all keys related to the Python dictionary.

# Update the keys() method if update the dictionary technology={"Course":"python","Fee":4000,"Duration":"60 days"} print(technology.keys()) # Output: # dict_keys(['Course', 'Fee', 'Duration']) technology.update({"tutor": "Richard"}) print(technology.keys()) # Output: #dict_keys(['Course', 'Fee', 'Duration', 'tutor'])

2.7 pop()

The pop() method of Python dictionary (dict) is used to remove the element from the dictionary by dict key and return the value related to the removed key. If a key does not exist in the dictionary and the default value is specified, then returns the default value; else throws a KeyError. For example,

# Delete the key element using pop() method technology = { 'course':'python', 'fee': 4000, 'duration': '60 days' } item=technology.pop('fee') print("Popped value is:",item) print("The dictionary is:" ,technology) # Outputs: # Popped value is: 4000 # The dictionary is: {'course': 'python', 'duration': '60 days'}

2.8 popitem()

popitem() is a built-in method in the python dictionary that is used to remove and return the last key-value pair from the dict. It follows the Last In First Out approach. If the dictionary is empty, it returns a KeyError.

# Remove last item using popitem() technology = {'course': 'python', 'fee': 4000, 'duration': '45 days'} element=technology.popitem() print("Removed element:",element) print(technology) # Output: # Removed element: ('duration', '45 days') # {'course': 'python', 'fee': 4000}

2.9 setdefault()

Using the setdefault() method we can set the default value to the key of the Python dictionary. It returns a value if the key is present in the dictionary. Otherwise, it inserts the key with the value specified into the dictionary. If a value is not specified, it set the default value None.

# Key is not present in the dictionary, value not specified technology = {"course": "python", "fee": 4000} duration = technology.setdefault("duration") print('Technology:', technology) print('Duration:',duration) # Output: Technology: # {'course': 'python', 'fee': 4000, 'duration': None} # Duration: None

2.10 update()

Using the Python Dictionary update() method we can update the dictionary by using another dictionary or an iterable of key-value pairs(such as a tuple). If the key is already present, this method updates the existing key with the new value from the iterable value. For example,

# Using update() update the dictionary Technology = {'course': 'python', 'fee':4000} Technology.update({'duration':'45days'}) print("Updated Technology:",Technology) # Outputs: # Updated Technology: {'course': 'python', 'fee': 4000, 'duration': '45days'}

2.11 values()

Python dictionary values() method returns a view object that contains a list of all values stored in the dictionary. This method is useful if you want to iterate over only the values in the dictionary. Any changes in the dictionary will reflect in the view object.

# Using Values() to get values from the dictionary technology = { 'course':'python', 'fee': 4000, 'duration': '60 days' } print(technology.values()) # Outputs: # dict_values(['python', 4000, '60 days'])

3. Conclusion

In this article, I have explained Python dictionary methods. As well, I have explained the benefits of these methods with working examples and output. I hope this gives you a better understanding of what you can do with python dictionary.

Happy Learning !!

References

  • https://docs.python.org/3/tutorial/datastructures.html