Iago-lito Iago-lito - 4 years ago 153
Python Question

"Name * not defined" in nested python comprehension

I have gathered information in a dictionnary of this form:

dico = {
'key1': ('el1', 'el2', 'el3'),
'key2': ('el4',),
'key3': ('el5', 'el6'),

I wish to iterate over it in such a way that this would produce:

>>> for i in gen:
... print(i)
('key1', 'el1')
('key1', 'el2')
('key1', 'el3')
('key2', 'el4')
('key3', 'el5')
('key3', 'el6')

So here is how I build

gen = ((key, value) for value in values for key, values in dico.items())

But this throws a

NameError: name 'values' is not defined

What is wrong? How should I do?

Answer Source

Reverse the order so that the names resolve:

gen = ((key, value) for (key, values) in dico.items() for value in values)

The for loops should be in the same order as if you'd write:

for key, values in dico.items():
    for value in values:
        yield key, value
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download