Common Dictionary Methods

Python dictionaries have several built-in methods that allow you to manipulate them efficiently.

get() Method

Returns the value of the specified key.

Example: Using get()

# Using get()
person = {"name": "Praveen", "age": 24}
age = person.get("age")
print("Age:", age)

Age: 24

keys() Method

Returns a view object containing the dictionary's keys.

values() Method

Returns a view object containing the dictionary's values.

items() Method

Returns a view object containing the dictionary's key-value pairs.

update() Method

Updates the dictionary with the specified key-value pairs.

pop() Method

Removes the element with the specified key.

Example: Using pop()

# Using pop()
person = {"name": "Williams", "age": 29}
age = person.pop("age")
print("Popped Age:", age)
print("Person Dictionary:", person)

Popped Age: 29

Person Dictionary: {'name': 'Williams'}

popitem() Method

Removes the last inserted key-value pair.

clear() Method

Removes all the elements from the dictionary.

copy() Method

Returns a shallow copy of the dictionary.

fromkeys() Method

Creates a new dictionary from the given sequence of keys and a value.

Example: Using fromkeys()

# Using fromkeys()
keys = ['name', 'age', 'city']
default_value = None
new_dict = dict.fromkeys(keys, default_value)
print("New Dictionary:", new_dict)

New Dictionary: {'name': None, 'age': None, 'city': None}

setdefault() Method

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

Example: Using setdefault()

# Using setdefault()
person = {"name": "John"}
age = person.setdefault("age", 26)
print("Age:", age)
print("Person Dictionary:", person)

Age: 26

Person Dictionary: {'name': 'John', 'age': 26}

Explanation: These methods provide various ways to interact with and manipulate dictionaries, allowing for efficient data management.