accessing dictionary keys and values in python

You can access dictionary keys and values in Python using the following syntax:

main.py
#Creating a dictionary
my_dict = {'apple': 10, 'banana': 5, 'orange': 15}

#Accessing keys
print(my_dict.keys())

#Accessing values
print(my_dict.values())

#Accessing both keys and values together
print(my_dict.items())

#Accesing values using a key
print(my_dict['apple'])
275 chars
15 lines

Output:

main.py
dict_keys(['apple', 'banana', 'orange'])
dict_values([10, 5, 15])
dict_items([('apple', 10), ('banana', 5), ('orange', 15)])
10
128 chars
5 lines

In the example above, the keys() method returns a list of all keys in the dictionary. The values() method returns a list of all values in the dictionary. The items() method returns a list of key-value pairs in the dictionary. You can access the value of a specific key in the dictionary by using the key in square brackets like my_dict['apple']. Here, it will return the value of key 'apple' which is 10.

related categories

gistlibby LogSnag