7

How could I get this working?

color_table = {"Red":[1,2,3], "Blue":[4,5,6]}

How can I access values individually?

color_table[Red].0 = 1
color_table[Red].1 = 2
color_table[Red].2 = 3
color_table[Blue].0 = 4
color_table[Blue].1 = 5  

I want to assign these values to a variable. For ex:

x = color_table[Red].0
wjandrea
  • 28,235
  • 9
  • 60
  • 81
user968000
  • 1,765
  • 3
  • 22
  • 31

3 Answers3

6

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.

Stephen
  • 1,498
  • 17
  • 26
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
Ijaz Ahmad
  • 11,198
  • 9
  • 53
  • 73
0
color_table = {"Red":[1,2,3], "Blue":[4,5,6]}

for key in color_table.keys():
    for i in color_table.get(key):
        print("Key {} Value {}".format(key,i))

Here, .keys() is a method which allows to access keys of a dictionary. .get(key) is method by how we can access every key one by one. Then by using nested loop we can access every key and its values one by one remained in a list.

roktim
  • 81
  • 2
  • 8
  • 6
    Welcome to Stack Overflow. Code dumps without any explanation are rarely helpful. Stack Overflow is about learning, not providing snippets to blindly copy and paste. Please [edit] your question and explain how it works better than what the OP provided. – ChrisGPT was on strike May 14 '20 at 00:35