Dictionary Methods

Introduction

The Python dictionary is a versatile data structure that stores elements as key-value pairs. One feature that makes dictionaries an invaluable asset in a developer’s toolset is its collection of inherent methods. As in Python, everything is an object, a Python dictionary has a set of built-in methods that can be invoked on dictionary objects to perform various tasks.

Let’s go through some of the most commonly used Python dictionary methods.

keys()

The keys() method returns a new object (a view) of the dictionary’s keys.

1dict1 = {"apple": 1, "banana": 2, "cherry": 3}
2print(dict1.keys())  # Output: dict_keys(['apple', 'banana', 'cherry'])

values()

The values() method returns a new object (a view) of the dictionary’s values.

1print(dict1.values())  # Output: dict_values([1, 2, 3])

items()

The items() method returns a new object (a view) of the dictionary’s items in (key, value) format.

1print(dict1.items())  # Output: dict_items([('apple', 1), ('banana', 2), ('cherry', 3)])

get()

The get() method fetches the value of a given key from the dictionary. It returns None if the key is not found.

1print(dict1.get("apple"))  # Output: 1
2print(dict1.get("mango"))  # Output: None

update()

The update() method adds a new item to the dictionary if the key is not present. If the key is present, it updates the key with the new value.

1dict1.update({"mango": 4})
2print(dict1)  # Output: {'apple': 1, 'banana': 2, 'cherry': 3, 'mango': 4}

clear()

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

1dict1.clear()
2print(dict1)  # Output: {}

Did you know?

Dictionary methods like keys(), values(), and items() return “view” objects. These are dynamic and will reflect any changes to the dictionary.

These dictionary methods provide you with powerful tools to manipulate and extract data from dictionaries. Python’s rich set of inbuilt dictionary methods make it easy and efficient to work with dictionaries.