Dictionary Methods in Python

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.

clear()

Removes all items from the dictionary.

{}

copy()

Creates and returns a separate copy of the dictionary.

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

fromkeys()

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

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

get()

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

22

items()

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

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

keys()

Returns a view object containing all dictionary keys.

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

pop()

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

{'pencil': 20}

popitem()

Removes and returns the last inserted key–value pair.

{'order1': 250}

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}

update()

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

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

values()

Returns a view object containing all dictionary values.

dict_values([120, 40])

Our website uses cookies to enhance your experience. Learn More
Accept !