close

How can i access list values in a dictionary

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How can i access list values in a dictionary in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How can i access list values in a dictionary?

  1. How can i access list values in a dictionary?

    You're close. Make sure you refer to keys like “Red” and “Blue” by surrounding them with quotes in the key reference. Like so: color_table["Red"]

  2. i access list values in a dictionary

    You're close. Make sure you refer to keys like “Red” and “Blue” by surrounding them with quotes in the key reference. Like so: color_table["Red"]

Method 1

You’re close. Make sure you refer to keys like “Red” and “Blue” by surrounding them with quotes in the key reference. Like so: color_table["Red"]

This will return the value for that key in the dictionary which, in this case, is a list.

Thus, you can reference members of that list by appending an index operator to the statement above like so: color_table["Red"][0] to reference the first element in that list.

To assign it to a variable, simply use the assignment operator x = color_table["Red"][0].

You can also visit Python’s documentation site for information on the differences between dictionaries, lists, etc. in Python.

Method 2

Use pythonic way:

color_table = {"Red":[1,2,3], "Blue":[4,5,6]}
>>> for val in color_table.values():
...   for item in val:
...     print item
... 
4
5
6
1
2
3

OR

>>> for val in color_table.values():
    ...   for item in val:
    ...     # do something with item

if you just want to statically assign value:

color_table['Red'][0] = value

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read