Python Dictionary Methods

Python dictionaries provide built-in methods to add, update, remove, and access key-value pairs. update() The update() method updates existing values or adds new key-value pairs. Syntax Example Output: pop() The pop() method removes a specified key and returns its value. Syntax Example Output: popitem() The popitem() method removes the last inserted item. Syntax Example Output: […]

2 mins read Lesson 15 of 56 27% through track

Python dictionaries provide built-in methods to add, update, remove, and access key-value pairs.

update()

The update() method updates existing values or adds new key-value pairs.

Syntax

dictionary_name.update({key: value})

Example

student = {
    "name": "John",
    "age": 20
}

student.update({"age": 21})

print(student)

Output:

{'name': 'John', 'age': 21}

pop()

The pop() method removes a specified key and returns its value.

Syntax

dictionary_name.pop(key)

Example

student = {
    "name": "John",
    "age": 20
}

student.pop("age")

print(student)

Output:

{'name': 'John'}

popitem()

The popitem() method removes the last inserted item.

Syntax

dictionary_name.popitem()

Example

student = {
    "name": "John",
    "age": 20
}

student.popitem()

print(student)

Output:

{'name': 'John'}

clear()

The clear() method removes all items from a dictionary.

Syntax

dictionary_name.clear()

Example

student = {
    "name": "John",
    "age": 20
}

student.clear()

print(student)

Output:

{}

copy()

The copy() method creates a copy of a dictionary.

Syntax

dictionary_name.copy()

Example

student = {
    "name": "John",
    "age": 20
}

new_student = student.copy()

print(new_student)

Output:

{'name': 'John', 'age': 20}

setdefault()

The setdefault() method returns the value of a key. If the key does not exist, it inserts the key with the specified value.

Syntax

dictionary_name.setdefault(key, default_value)

Example

student = {
    "name": "John"
}

student.setdefault("age", 20)

print(student)

Output:

{'name': 'John', 'age': 20}

fromkeys()

The fromkeys() method creates a new dictionary from a sequence of keys.

Syntax

dict.fromkeys(keys, value)

Example

keys = ("name", "age", "city")

student = dict.fromkeys(keys, "Not Set")

print(student)

Output:

{'name': 'Not Set', 'age': 'Not Set', 'city': 'Not Set'}

Summary

  • update() updates or adds key-value pairs.
  • pop() removes a specific key.
  • popitem() removes the last inserted item.
  • clear() removes all dictionary items.
  • copy() creates a duplicate dictionary.
  • setdefault() returns a value or creates a key if it does not exist.
  • fromkeys() creates a new dictionary using a list of keys.