Python Dictionary Methods

Python dictionaries are versatile data structures that store key-value pairs, allowing for efficient data retrieval and manipulation. To enhance their functionality, Python provides a variety of built-in methods specifically designed for dictionaries. Below is an overview of these methods, along with their descriptions and usage examples.

1. clear()

Description: Removes all elements from the dictionary, resulting in an empty dictionary.

Syntax: dictionary.clear()

Example:

# Initializing a dictionary
car = {"brand": "Ford", "model": "Mustang", "year": 1964}

# Clearing the dictionary
car.clear()
print(car)  # Output: {}

2. copy()

Description: Returns a shallow copy of the dictionary.

Syntax: dictionary.copy()

Example:

# Original dictionary
car = {"brand": "Ford", "model": "Mustang", "year": 1964}

# Creating a copy
car_copy = car.copy()
print(car_copy)  # Output: {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}

3. fromkeys()

Description: Creates a new dictionary with specified keys, each assigned to a specified value.

Syntax: dict.fromkeys(keys, value)

Example:

# Defining keys
keys = ('brand', 'model', 'year')

# Creating a new dictionary with default value None
new_car = dict.fromkeys(keys)
print(new_car)  # Output: {'brand': None, 'model': None, 'year': None}

# Creating a new dictionary with a specified value
new_car = dict.fromkeys(keys, 'Unknown')
print(new_car)  # Output: {'brand': 'Unknown', 'model': 'Unknown', 'year': 'Unknown'}

4. get()

Description: Returns the value associated with a specified key. If the key is not found, it returns a default value (default is None).

Syntax: dictionary.get(key, default=None)

Example:

# Dictionary of car details
car = {"brand": "Ford", "model": "Mustang", "year": 1964}

# Accessing existing key
model = car.get("model")
print(model)  # Output: Mustang

# Accessing non-existing key with default value
color = car.get("color", "Not Specified")
print(color)  # Output: Not Specified

5. items()

Description: Returns a view object displaying a list of the dictionary’s key-value tuple pairs.

Syntax: dictionary.items()

Example:

# Dictionary of car details
car = {"brand": "Ford", "model": "Mustang", "year": 1964}

# Getting items
car_items = car.items()
print(car_items)  # Output: dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])

6. keys()

Description: Returns a view object displaying a list of all the keys in the dictionary.

Syntax: dictionary.keys()

Example:

# Dictionary of car details
car = {"brand": "Ford", "model": "Mustang", "year": 1964}

# Getting keys
car_keys = car.keys()
print(car_keys)  # Output: dict_keys(['brand', 'model', 'year'])

7. pop()

Description: Removes the specified key and returns its corresponding value. If the key is not found, it raises a KeyError unless a default value is provided.

Syntax: dictionary.pop(key, default)

Example:

# Dictionary of car details
car = {"brand": "Ford", "model": "Mustang", "year": 1964}

# Popping an existing key
model = car.pop("model")
print(model)  # Output: Mustang
print(car)    # Output: {'brand': 'Ford', 'year': 1964}

# Popping a non-existing key with default value
color = car.pop("color", "Not Specified")
print(color)  # Output: Not Specified

8. popitem()

Description: Removes and returns the last inserted key-value pair as a tuple. In versions prior to Python 3.7, it removes an arbitrary item due to unordered nature of dictionaries.

Syntax: dictionary.popitem()

Example:

# Dictionary of car details
car = {"brand": "Ford", "model": "Mustang", "year": 1964}

# Popping the last item
last_item = car.popitem()
print(last_item)  # Output: ('year', 1964)
print(car)        # Output: {'brand': 'Ford', 'model': 'Mustang'}

9. setdefault()

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

Syntax: dictionary.setdefault(key, default=None)

Example:

# Dictionary of car details
car = {"brand": "Ford", "model": "Mustang"}

# Using setdefault on an existing key
brand = car.setdefault("brand", "Unknown")
print(brand)  # Output: Ford

# Using setdefault on a non-existing key
color = car.setdefault("color", "Red")
print(color)  # Output: Red
print(car)    # Output: {'brand': 'Ford', 'model': 'Mustang', 'color': 'Red'}

10. update()

Description: Updates the dictionary with elements from another dictionary or an iterable of key-value pairs. Existing keys will have their values updated; new keys will be added.

Syntax: dictionary.update([other])

Example:

# Original dictionary
car = {"brand": "Ford", "model": "Mustang", "year": 1964}

# Dictionary to update with
update_info = {"color": "Red", "year": 2020}

# Updating the original dictionary
car.update(update_info)
print(car)  # Output: {'brand': 'Ford', 'model': 'Mustang', 'year': 2020, 'color': 'Red'}

Keep Learning 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *