Accessing Key and Values in a Dictionary
tags: #python/documentation/dictionaries
The usual indexing method does not work with Python dictionaries in retrieving the key-value pair. Instead, it will attempt to retrieve the value associated with the value passed in the index operator. In a dictionary, you access values by their keys, not by numerical indices.
Accessing a Key-Value Pair
1. Using the items() Method
d.items()
The items() method returns a view object. The view object contains the key-value pairs of the dictionary, as tuples in a list.
Example:
# Example dictionary
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
# Using items() to create a list of tuples
items_list = list(my_dict.items())
# Displaying the output
print("List of items:", items_list)
[('name', 'John'), ('age', 25), ('city', 'New York')]
Accessing Values
1. Using the Index Operator
To access a value associated with a key, we can use the index operator:
d[key]
Example:
person = {
'first_name': 'John',
'last_name': 'Doe',
'age': 25,
'favorite_colors': ['blue', 'green'],
'active': True
}
print(person['first_name'])
print(person['last_name'])
Output:
John
Doe
2. Using the values() Method
To access values in a dictionary, we can use the values() method:
d.values()
This returns a view object that displays a list of all the values in the dictionary. We can use a For Loop to store the values returned with values() in a list:
vals = []
for i in d.values():
vals.append(i)
This iterates through the values of the dictionary d and appends each value to the list vals.
Alternatively, we can store it in a list object directly:
list(d.values())
3. Using the items() Method
Similarly, we can get a list of values using the items() method:
vals = []
for key, value in d.items(): # Tuple unpacking/multiple assignment
vals.append(value)
4. Using the get() Method (Return value if not exists)
The get() method returns the value of the item associated with the specified key:
d.get(keyname, value)
keyname(required): Associated key of the value which you want to retreieve.value(optional): A value to return if the specified key does not exist. Default value isNone.
Example:
person = {
'first_name': 'John',
'last_name': 'Doe',
'age': 25,
'favorite_colors': ['blue', 'green'],
'active': True
}
ssn = person.get('ssn')
print(ssn)
Output:
None
Accessing the Keys
1. Using the keys() Method
The keys() method returns a view object. The view object contains the keys of the dictionary, as a list.
d.keys()
To get a list of keys:
list(d.keys())
2. Using the items() Method
Similarly, we can get a list of keys using the items() method:
keys = []
for key, value in d.items(): # Tuple unpacking/multiple assignment
keys.append(key)