Reputation: 13
I'm trying to create a dictionary as below. What I want to do is:
NestedList = [["key1","key2"],["val1a","val2a"],["val1b","val2b"]]
mydict = {a:{b:c} for a,b,c in NestedList}
print mydict
Runtime error (ValueErrorException): need more than 2 values to unpack
This doesnt work as it wants to unpack the first list into a,b,c rather than unpack the first index of each list into a,b,c. What does work is this:
mydict = {a:{b:c} for a,b,c in zip(NestedList[0],NestedList[1],NestedList[2])}
print mydict
{'key1': {'val1a': 'val1b'}, 'key2': {'val2a': 'val2b'}}
However, I don't want to have to unpack the nested list as above. How do I rewrite this to avoid the unpacking and zipping?
N.B I can avoid this in this instance by redefining my NestedList, however the point in general still stands - how would I do this when I can't just rewrite my input list?
Upvotes: 0
Views: 146
Reputation: 1647
what is about:
NestedList = [["key1","key2"],["val1a","val2a"],["val1b","val2b"]]
mydict = {a:{b:c} for a,b,c in zip(*NestedList)}
print(mydict)
Upvotes: 2