Python From Beginner to Advanced

0% completed

Previous
Next
Python - Dictionary Methods

Dictionaries in Python are versatile data structures that allow for efficient storage and retrieval of key-value pairs. To facilitate various operations associated with dictionaries, Python provides a comprehensive set of methods. These methods enhance the functionality of dictionaries, enabling manipulation, access, and modification of their contents easily.

Dictionary Methods

Here is a table summarizing some of the most commonly used dictionary methods along with their descriptions:

MethodDescriptionTime Complexity
dict.clear()Removes all elements from the dictionary.O(1)
dict.copy()Returns a shallow copy of the dictionary.O(n)
dict.fromkeys(seq, value)Creates a new dictionary with keys from seq and values set to value.O(n)
dict.get(key, default=None)Returns the value for key if key is in the dictionary, else default.O(1)
dict.items()Returns a view of the dictionary's key-value pairs.O(1)
dict.keys()Returns a view of the dictionary's keys.O(1)
dict.pop(key)Removes the item with the specified key and returns its value.O(1)
dict.popitem()Removes the last inserted key-value pair and returns it.O(1)
dict.setdefault(key, default=None)Returns the value of key. Sets the value of key to default if key is not in dictionary.O(1)
dict.update(dict2)Adds dictionary dict2's key-values pairs to the dictionary.O(n)
dict.values()Returns a view of the dictionary's values.O(1)

Example 1: Utilizing Basic Dictionary Methods

In this example, we will demonstrate the use of get, update, and clear methods.

Python3
Python3

. . . .

Explanation:

  • info.get('name') retrieves the value associated with the key 'name'. If 'name' did not exist, it would return None.
  • info.update({'age': 29, 'phone': '123-456-7890'}) adds a new key-value pair ('phone') and updates the existing 'age' value in the dictionary.
  • info.clear() removes all items from the dictionary, leaving it empty.

Example 2: Advanced Dictionary Methods

In this example, we will explore the use of pop, items, and fromkeys methods.

Python3
Python3

. . . .

Explanation:

  • dict.fromkeys(keys, default_value) creates a new dictionary with keys from the list keys and sets all of their values to default_value.
  • new_dict.pop('b') removes the key 'b' from the dictionary and returns its value, which is displayed.
  • new_dict.items() returns a view of the dictionary's items, showing remaining key-value pairs.

These examples illustrate the utility of dictionary methods in managing and manipulating dictionaries efficiently. Understanding these methods can greatly enhance your ability to work with data structures in Python.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next