A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python/python-dictionary-items-method/ below:

Python Dictionary items() method - GeeksforGeeks

Python Dictionary items() method

Last Updated : 11 Jul, 2025

items() method in Python returns a view object that contains all the key-value pairs in a dictionary as tuples. This view object updates dynamically if the dictionary is modified.

Example:

Python
d = {'A': 'Python', 'B': 'Java', 'C': 'C++'}

# using items() to get all key-value pairs
items = d.items()

print(items)

Output
dict_items([('A', 'Python'), ('B', 'Java'), ('C', 'C++')])

Explanation: items() method returns a dict_items view object containing all key-value pairs in the form of tuples.

Note : items() method is only available for dictionary objects. If called on a non-dictionary object, it will raise an AttributeError.

items() syntax

dict.items()

Here, dict is the dictionary from which the key-value pairs are retrieved.

Parameters:

Return value:

Examples of items() Example 1: Iterating over key-value pairs Python
d = {'A': 'Python', 'B': 'Java', 'C': 'C++'}

# using items() to iterate over dictionary
for key, value in d.items():
    print(f"Key: {key}, Value: {value}")

Output
Key: A, Value: Python
Key: B, Value: Java
Key: C, Value: C++

Explanation: items() method allows easy unpacking of key-value pairs using tuple unpacking inside a loop.

Example 2: Dynamic nature of items() Python
d = {'A': 'Python', 'B': 'Java'}

# getting items
items = d.items()

# adding a new key-value pair
d['C'] = 'C++'

print(items)

Output
dict_items([('A', 'Python'), ('B', 'Java'), ('C', 'C++')])

Explanation: When a new key-value pair is added to the dictionary, the items() view object updates automatically to include the new pair.

Example 3: Converting items() to a list Python
d = {'A': 'Python', 'B': 'Java', 'C': 'C++'}

# converting items to a list
items_list = list(d.items())

print(items_list)

Output
[('A', 'Python'), ('B', 'Java'), ('C', 'C++')]

Explanation: We convert the dict_items object into a list of tuples, allowing for indexing, sorting or other list operations.



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4