denvaar denvaar - 3 months ago 12
Python Question

Iterate a tuple with dict inside

Having trouble iterating over tuples such as this:

t = ('a','b',{'c':'d'})

for a,b,c in t:
print(a,b,c) # ValueError: not enough values to unpack (expected 3, got 1)

for a,b,*c in t:
print(a,b,c) # ValueError: not enough values to unpack (expected 2, got 1)

for a,b,**c in t:
print (a,b,c) # Syntax error (can't do **c)


Anyone know how I can preserve the dictionary value? I would like to see
a='a', b='b', and c={'c':'d'}

Answer

You'd need to put t inside some other iterable container:

for a, b, c in [t]:
    print(a, b, c)

The problem with your attempts is that each on is iterating over a single element from t and trying to unpack that. e.g. the first turn of the loop is trying to unpack 'a' into three places (a, b and c).


Obviously, it's also probably better to just unpack directly (no loop required):

a, b, c = t
print(a, b, c)
Comments