Last updated: Apr 9, 2024
Reading timeยท5 min
To get the index of a key in a dictionary:
list()
class to convert the dictionary to a list of keys.list.index()
method to get the position of the key in the
dictionary.list.index()
method will return the index of the specified key.my_dict = { 'id': 1, 'name': 'Bobbyhadz', 'age': 30, } index = None if 'name' in my_dict: index = list(my_dict).index('name') print(index) # ๐๏ธ 1 key = list(my_dict)[1] print(key) # ๐๏ธ name value = list(my_dict.values())[1] print(value) # ๐๏ธ Bobbyhadz
Once we find the index of the key in a dictionary, we have to convert the dictionary to a list to access it.
We used the list()
class to convert the dictionary to a list of keys.
my_dict = { 'id': 1, 'name': 'Bobbyhadz', 'age': 30, } print(list(my_dict)) # ๐๏ธ ['id', 'name', 'age'] print(list(my_dict.keys())) # ๐๏ธ ['id', 'name', 'age']
We could have also used the dict.keys()
method to be more explicit.
The dict.keys method returns a new view of the dictionary's keys.
The last step is to use the list.index()
method to get the position of the key
in the dictionary.
my_dict = { 'id': 1, 'name': 'Bobbyhadz', 'age': 30, } index = None if 'name' in my_dict: index = list(my_dict).index('name') print(index) # ๐๏ธ 1
list.index()
method returns the index of the first item whose value is equal to the provided argument.The method raises a ValueError
if there is no such item in the list.
We used an if
statement to check if the key exists in the dictionary, so the
list.index()
method will never throw a ValueError
.
You can use the index to get the key and value at the specific position.
my_dict = { 'id': 1, 'name': 'Bobbyhadz', 'age': 30, } index = None if 'name' in my_dict: index = list(my_dict).index('name') print(index) # ๐๏ธ 1 key = list(my_dict)[index] print(key) # ๐๏ธ name value = list(my_dict.values())[index] print(value) # ๐๏ธ Bobbyhadz
To get the key at the specific position, we just have to convert the dictionary to a list of keys and access the list at the index.
To get the value, we convert the dict.values()
view to a list and access it at
the index.
The dict.values() method returns a new view of the dictionary's values.
my_dict = {'id': 1, 'name': 'bobbyhadz'} print(my_dict.values()) # ๐๏ธ dict_values([1, 'bobbyhadz'])
Note that unless you have a good reason to access the keys and values in the dictionary using an index, using bracket notation is much more performant.
my_dict = { 'id': 1, 'name': 'Bobbyhadz', 'age': 30, 'address': { 'country': 'Chile' }, 'tasks': ['dev', 'test'] } print(my_dict['name']) # ๐๏ธ Bobbyhadz print(my_dict['address']) # ๐๏ธ {'country': 'Chile'} print(my_dict['address']['country']) # ๐๏ธ Chile print(my_dict['tasks'][0]) # ๐๏ธ dev
You can specify a key between the square brackets to access the corresponding value.
You can also use the dict.items()
method to get a dictionary key-value pair by
index.
my_dict = { 'id': 1, 'name': 'Bobbyhadz', 'age': 30, } index = 1 key, value = list(my_dict.items())[index] print(key) # ๐๏ธ name print(value) # ๐๏ธ Bobbyhadz
The dict.items() method returns a new view of the dictionary's items ((key, value) pairs).
my_dict = { 'id': 1, 'name': 'Bobbyhadz', 'age': 30, } # ๐๏ธ dict_items([('id', 1), ('name', 'Bobbyhadz'), ('age', 30)]) print(my_dict.items())
The dict_items
object is not subscriptable (cannot be accessed at an index),
so we used the list()
class to convert it to a list.
my_dict = { 'id': 1, 'name': 'Bobbyhadz', 'age': 30, } index = 1 key, value = list(my_dict.items())[index] print(key) # ๐๏ธ name print(value) # ๐๏ธ Bobbyhadz
Python indexes are zero-based, so the first item in a list has an index of 0
,
and the last item has an index of -1
or len(a_list) - 1
.
If you need to get the position of multiple keys in the dictionary, use a for loop.
my_dict = { 'id': 1, 'name': 'Bobbyhadz', 'age': 30, } keys = ['name', 'age'] for key in keys: if key in my_dict: # name - 1 # age - 2 print(f'{key} - {list(my_dict).index(key)}')
On each iteration, we check if the key is contained in the dictionary and print the corresponding index.
You can also use the enumerate()
function to access dictionary keys or values
by index.
my_dict = { 'id': 1, 'name': 'Bobbyhadz', 'age': 30, } index = 1 key = next( key for idx, key in enumerate(my_dict) if idx == index ) print(key) # ๐๏ธ name # ------------------------------------------------------ value = next( value for idx, value in enumerate(my_dict.values()) if idx == index ) print(value) # ๐๏ธ Bobbyhadz
The enumerate() function takes an iterable and returns an enumerate object containing tuples where the first element is the index and the second is the corresponding item.
my_dict = { 'id': 1, 'name': 'Bobbyhadz', 'age': 30, } for index, key in enumerate(my_dict): # 0 id # 1 name # 2 age print(index, key)
On each iteration, we check if the current index is equal to the specified index and return the corresponding key or value.
If you need to get all dictionary keys that have a specific value, use a list comprehension.
my_dict = { 'id': 1, 'name': 'Bobbyhadz', 'age': 30, 'salary': 30, } keys = [key for key, value in my_dict.items() if value == 30] print(keys) # ๐๏ธ ['age', 'salary']
List comprehensions are used to perform some operation for every element or select a subset of elements that meet a condition.
On each iteration, we check if the current value is equal to 30
and return the
result.
The keys
list only stores the keys of the items that have a value of 30
.
OrderedDict
class insteadAs of Python 3.7, the standard dict
class is guaranteed to preserve the
insertion order of keys.
You can check your version of python
by issuing the python --version
command.
python --version
If you use an older version (than 3.7), use the OrderedDict
class instead.
from collections import OrderedDict my_dict = OrderedDict( [('id', 1), ('name', 'Bobbyhadz'), ('age', 30)] ) key = list(my_dict)[1] print(key) # ๐๏ธ name value = list(my_dict.values())[1] print(value) # ๐๏ธ Bobbyhadz index = None if 'name' in my_dict: index = list(my_dict).index('name') print(index) # ๐๏ธ 1
The list()
class can also be used to convert the keys of an OrderedDict
to a
list.
Note that using the OrderedDict
class is only necessary if you use a version
older than Python 3.7.
Otherwise, use the native dict
class as it preserves insertion order.
You can learn more about the related topics by checking out the following tutorials: