+ 1
What's wrong with this code?
a = (1, 2, 3, 4) b = ("one", "two", "three", "four") c = ("i", "ii", "iii", "iv") d = zip(a, b, c) print(dict(d))
3 Answers
+ 13
the answer from Oma Falk could be misunderstood.
> the limitation is not the zip() function. it can take (theoretically) any number of arguments. using more than 2 arguments is no problem
when the output of the tuples are stored in a list, set or in a tuple.
> using output to a dict is an issue, if we process more than 2 arguments with zip. in this case values of a dict need to be enclosed in a
container format like list or tuple. this needs a modification of the code. we can use a nested zip() construct with a list comprehension.
# dic = {1: ['one', 'two'] } # this is a correct dict
# dic = {1: 'one', 'two' } # this is NOT a correct dict
a = (1, 2, 3, 4)
b = ("one", "two", "three", "four")
c = ("i", "ii", "iii", "iv")
print(list(zip(a, b, c)))
# result: [(1, 'one', 'i'), (2, 'two', 'ii'), (3, 'three', 'iii'), (4, 'four', 'iv')]
d = zip(a, [[i, j] for i, j in zip(b,c)])
print(dict(d))
# result: {1: ['one', 'i'], 2: ['two', 'ii'], 3: ['three', 'iii'], 4: ['four', 'iv']}
+ 5
Zip requires 2 arguments, not 3
d = zip(a, zip(b, c))
+ 4
Very fine explained Lothar đ