Get Dictionary Keys, Values, or Items in Python

Accessing the keys, values, or items of a dictionary allows you to retrieve specific information from the dictionary. In this blog post, we will explore different methods to get the keys, values, or items of a dictionary in Python.

Method 1: Using the keys(), values(), or items() Methods

# Method 1: Using the keys(), values(), or items() Methods
my_dict = {"name": "John", "age": 30, "city": "New York"}
keys = my_dict.keys()
values = my_dict.values()
items = my_dict.items()
print("Keys:", keys)
print("Values:", values)
print("Items:", items)

Output:

Keys: dict_keys([‘name’, ‘age’, ‘city’])

Values: dict_values([‘John’, 30, ‘New York’])

Items: dict_items([(‘name’, ‘John’), (‘age’, 30), (‘city’, ‘New York’)])

Method 2: Converting to Lists

# Method 2: Converting to Lists
my_dict = {"name": "John", "age": 30, "city": "New York"}
key_list = list(my_dict.keys())
value_list = list(my_dict.values())
item_list = list(my_dict.items())
print("Keys as list:", key_list)
print("Values as list:", value_list)
print("Items as list:", item_list)

Output:

Keys as list: [‘name’, ‘age’, ‘city’]

Values as list: [‘John’, 30, ‘New York’]

Items as list: [(‘name’, ‘John’), (‘age’, 30), (‘city’, ‘New York’)]