How do I index into a dictionary in Python?

How do I index into a dictionary in Python?

I have the following dictionary:

colors = {
    "blue": "5",
    "red": "6",
    "yellow": "8",
}

How can I index the first entry in the dictionary?

Using colors[0] will result in a KeyError because dictionaries are unordered collections. How can I achieve this with dictionary index in Python?

You can convert the dictionary keys to a list and access the first item using its index.

colors = {
    "blue": "5",
    "red": "6",
    "yellow": "8",
}

first_key = list(colors.keys())[0]  # Index the first key
first_value = colors[first_key]  # Access the corresponding value
print(first_key, first_value)

You can use iter() to get an iterator over the dictionary’s keys and next() to retrieve the first key-value pair.

colors = {
    "blue": "5",
    "red": "6",
    "yellow": "8",
}

first_key = next(iter(colors))  # Get the first key
first_value = colors[first_key]  # Access the corresponding value
print(first_key, first_value)

You can use enumerate() to loop through the dictionary and retrieve the first item.

colors = {
    "blue": "5",
    "red": "6",
    "yellow": "8",
}

This approach help you index into a dictionary, which is unordered, using methods that simulate the behavior of indexing, while working within the dictionary’s structure.

for idx, (key, value) in enumerate(colors.items()):
    if idx == 0:
        print(key, value)  # This prints the first key-value pair
        break