How can I access the values in a Python dictionary?

Published on Aug. 22, 2023, 12:16 p.m.

To access the values in a Python dictionary, you can use the keys of the dictionary as indices. You can do this by specifying the key inside the square brackets after the dictionary name.

Here is an example:

my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}

# Access a value by its key
print(my_dict['key1'])    # Output: 'value1'

# You can also use the get() method to access a value by its key
print(my_dict.get('key2'))  # Output: 'value2'

Note that if the key does not exist in the dictionary, using the key as an index or calling the get() method will result in a KeyError or None, respectively.

To access all the values in a dictionary, you can use the values() method. This returns a view object that you can iterate over using a loop, or convert to a list or tuple:

# Access all the values in a dictionary
values = my_dict.values()
print(values)    # Output: dict_values(['value1', 'value2', 'value3'])

# Loop over the view object
for value in values:
    print(value)

# Convert the view object to a list or tuple
value_list = list(my_dict.values())
value_tuple = tuple(my_dict.values())

This will output:

value1
value2
value3

Tags: