How to Retrieve a List of Keys and Values in Python?

Estimated read time 1 min read

To retrieve a list of keys and values from a dictionary in Python, you can use the keys() and values() methods. Here’s an example:

my_dict = {
    "name": "John",
    "age": 30,
    "city": "New York"
}

keys_list = list(my_dict.keys())
values_list = list(my_dict.values())

print(keys_list)    # Output: ['name', 'age', 'city']
print(values_list)  # Output: ['John', 30, 'New York']

In this example, we have a dictionary my_dict with key-value pairs. To retrieve a list of keys, you can use the keys() method of the dictionary, which returns a view object representing the keys. By converting this view object to a list using the list() function, you obtain a list of keys.

Similarly, to retrieve a list of values, you can use the values() method, which returns a view object representing the values of the dictionary. Again, by converting this view object to a list, you get a list of values.

You can then use the keys_list and values_list variables in your code as needed.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply