Categories
Python Answers

How to access elements of Python dictionary by index?

Spread the love

Sometimes, we want to access elements of Python dictionary by index

In this article, we’ll look at how to access elements of Python dictionary by index.

How to access elements of Python dictionary by index?

To access elements of Python dictionary by index, we can use the key to access the item.

For instance, we write

my_dict = {
    "Apple": {"American": "16", "Mexican": 10, "Chinese": 5},
    "Grapes": {"Arabian": "25", "Indian": "20"},
}

a = my_dict["Apple"]

We use my_dict["Apple"] to get the value of the 'Apple' key in my_dict.

Therefore, a is {"American": "16", "Mexican": 10, "Chinese": 5}.

Conclusion

To access elements of Python dictionary by index, we can use the key to access the item.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *