How to Access Dictionary Keys and Values by Index in Python
Dictionaries in Python are inherently unordered collections (prior to Python 3.7). While you typically access dictionary items by their keys, there are situations where you might want to access them by their insertion order or simulate an index-based lookup.
This guide explains why direct indexing (like my_dict[1]
) doesn't work with dictionaries and demonstrates the correct ways to achieve similar results using list()
, dict.keys()
, dict.values()
, dict.items()
, and enumerate()
.
Why Direct Indexing Doesn't Work on Dictionaries
Unlike lists or tuples, standard Python dictionaries (prior to version 3.7) do not have a defined order. Therefore, accessing elements by numerical index (like my_dict[0]
) is not supported and will raise a KeyError
. From Python 3.7 onwards, dictionaries do preserve insertion order, but they are still not designed for indexed access. Accessing by key is always the preferred method.
my_dict = {
'id': 1,
'name': 'TomNolan',
'age': 25,
}
# print(my_dict[0]) # Raises a KeyError
- In the example above, using
my_dict[0]
will cause aKeyError
exception, because0
is not one of the dictionary's keys.
Accessing Keys by Index
To get a specific key by its position (based on insertion order), convert the dictionary's keys to a list:
my_dict = {
'id': 1,
'name': 'TomNolan',
'age': 25,
}
index = 1
key = list(my_dict.keys())[index] # Or just list(my_dict)[index]
print(key) # Output: name
list(my_dict.keys())
or the simpler formlist(my_dict)
creates a list of the dictionary's keys in insertion order (guaranteed in Python 3.7+).[index]
then accesses the key at the desired position within that list.
Accessing Values by Index
To get a specific value by its position, convert the dictionary's values to a list:
my_dict = {
'id': 1,
'name': 'TomNolan',
'age': 25,
}
index = 1
value = list(my_dict.values())[index]
print(value) # Output: TomNolan
- The
dict.values()
method returns the values in the dictionary, and thelist()
constructor transforms them into a list so they can be accessed using an index.
Accessing Key-Value Pairs by Index
To get both the key and value at a specific position, convert the dictionary's items to a list:
my_dict = {
'id': 1,
'name': 'TomNolan',
'age': 25,
}
index = 1
key, value = list(my_dict.items())[index]
print(key) # Output: name
print(value) # Output: TomNolan
list(my_dict.items())
creates a list of (key, value) tuples.key, value = ...[index]
unpacks the tuple at the specified index into separatekey
andvalue
variables.
Getting Keys for a Specific Value
To find all keys associated with a specific value, use a list comprehension:
my_dict = {
'id': 1,
'name': 'TomNolan',
'age': 25,
'salary': 25,
}
keys = [key for key, value in my_dict.items() if value == 25]
print(keys) # Output: ['age', 'salary']
Using enumerate()
for Key and Value Access
You can iterate over the keys or values, and use enumerate()
to have access to the index:
my_dict = {
'id': 1,
'name': 'TomNolan',
'age': 25,
}
index = 1
key = next(
key for idx, key in enumerate(my_dict)
if idx == index
)
print(key) # Output: name
value = next(
value for idx, value in enumerate(my_dict.values())
if idx == index
)
print(value) # Output: TomNolan
OrderedDict
(for Python versions before 3.7)
In versions of Python before 3.7, standard dictionaries did not guarantee insertion order. If you need ordered dictionaries in older Python versions, use collections.OrderedDict
:
from collections import OrderedDict
my_dict = OrderedDict(
[('id', 1), ('name', 'TomNolan'), ('age', 25)]
)
key = list(my_dict)[1]
print(key) # Output: name
value = list(my_dict.values())[1]
print(value) # Output: TomNolan
Important: In Python 3.7 and later, regular dictionaries do preserve insertion order.
OrderedDict
is still useful for cases where you need to specifically rely on the order and want to make that intention explicit, or for compatibility with older Python versions.