3 Easy Ways to Access and Update a Dictionary Key by Index in Python

5/5 - (1 vote)

Python dictionaries are a versatile and powerful data structure. A common query is: “How can I access a dictionary key using its index and subsequently update the dictionary?” In this article, I’ll delve into this specific problem and explore the three most Pythonic solutions.

Problem Formulation

Given a dictionary, for instance:

skills = { "HTML": 90, "CSS": 80, "Python": 30 }

How can you:

  1. Access a key (e.g., "HTML") using its index?
  2. Update the dictionary to include a new key-value pair (e.g., "AI": 20)?

Method 1: Accessing a Key Using List Conversion

How to print a key in a dictionary using its index?

The most straightforward approach to accessing a key by its index involves converting the dictionary keys into a list.

keys_list = list(skills.keys())
key = keys_list[0]  # Accessing the first key



This method leverages the fact that dictionaries in Python 3.7+ maintain insertion order. However, it’s worth noting that in earlier versions of Python, dictionaries don’t guarantee order.

πŸ”— Recommended: How to Get First Key Value in a Dictionary

Method 2: Direct Key Access

If you’re aware of the key’s name, you can access its value directly without needing its index.

value = skills["HTML"]
print(f"HTML Progress Is {value}%")


HTML Progress Is 90%

This method is efficient and recommended when the key’s name is known.

Method 3: Updating the Dictionary

To add a new key-value pair to a dictionary, you can use a simple assignment operation.

skills["AI"] = 20


{'HTML': 90, 'CSS': 80, 'Python': 30, 'AI': 20}

This method seamlessly updates the dictionary, appending the new key-value pair.