Koen Koen - 1 year ago 70
Python Question

Get all values from each key

I just learned that:

coloring_dictionary = {}
coloring_dictionary.setdefault(key, [])

Would give me a dictionary with one key, that maps to three values(I need this in my project!). Great. Now I want to access and do some operations on each value for each key(in this case only one key, but this applies to several keys too.)

How should I write my for loop in order to get each value, one by one?
This is what I have so far:

for key in coloring_dictionary.keys():
for the_value in coloring_dictionary[key]:
print(coloring_dictionary[]????) #here I want to access A value
#do some operations on a value

Might be a simple answer to this, but I am stuck. Thanks in advance my fellow SO community!

Answer Source

The variable the_value should contain the value you`re looking for

for key in coloring_dictionary.keys():
    for the_value in coloring_dictionary[key]:
        print(the_value)  # As simple as that 

To explain what you`re doing:

Your dictionary looks something like this:

 coloring_dictionary = {
     "key1": [1,2,3,4],
     "key2": [5,6,7,8]

In the outer loop, you are iterating over all keys of that dictionary, so the variable key contains first 'key1' and then 'key2'.

In the inner loop you are iterating over all values that the dictionary holds at the position of key. In the case of 'key1' these are 1,2,3 and 4. These are stored in the_value.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download