Dictionary Methods in Python
gocourse.in Maintenance

We'll be back soon

Our CDN (cdn.gocourse.in) is currently unreachable. Some images, JavaScript, or CSS files may not load properly.

Estimated downtime: ~30 minutes

Dictionary Methods in Python

Kishore V

Dictionary Methods in Python

Python dictionaries come with several built-in methods that help you manage, access, and modify data efficiently. Below is a rewritten explanation of the most commonly used dictionary methods, along with fresh examples for better understanding.

1. clear()

Removes all items from the dictionary.

{}

2. copy()

Creates and returns a separate copy of the dictionary.

{'username': 'max_m', 'followers': 120}

3. fromkeys()

Creates a new dictionary using the specified keys and a single default value.

{'Math': 0, 'Science': 0, 'English': 0}

4. get()

Returns the value of a given key. If the key does not exist, it returns None (or a default value).

22

5. items()

Returns a view object containing key–value pairs as tuples.

dict_items([('Tom', 85), ('Jerry', 90)])

6. keys()

Returns a view object containing all dictionary keys.

dict_keys(['theme', 'language'])

7. pop()

Removes the item with the specified key and returns its value.

{'pencil': 20}

8. popitem()

Removes and returns the last inserted key–value pair.

{'order1': 250}

9. setdefault()

Returns the value of a key. If the key does not exist, it inserts the key with a default value.

{'mode': 'auto', 'timeout': 30}

10. update()

Updates the dictionary with new or existing key–value pairs.

{'name': 'Rahul', 'role': 'Senior Developer', 'salary': 80000}

11. values()

Returns a view object containing all dictionary values.

dict_values([120, 40])
Our website uses cookies to enhance your experience. Learn More
Accept !