Create dictionary from list of tuples using second element

Viewed 263

I have a list of lists of tuples like this:

new = [[('name', 'n1')], [('value', 'v1')], [('name', 'n2')], [('value', 'v2')], [('name', 'n3')], [('value', 'v3')]]

I want to map the first 'name' tuple to the first 'value' tuple, second to second, etc. What I have been doing is this:

res = dict(zip(new[0],new[1]))

which gives me {('name', 'n1'):('value', 'v1'), ('name', 'n2'):('value', 'v2'), ('name', 'n3'):('value':'v3')}. This is close, but I really just want this: {'n1':'v1', 'n2':'v2', 'n3':'v3'}. I just want the second element from the tuple. How can I do this?

3 Answers

try this,

print(dict((x[0][1], y[0][1]) for x, y in zip(new[::2], new[1::2])))

{'n1': 'v1', 'n2': 'v2', 'n3': 'v3'}

Here you go:

res= {new[2*i][0][1]:new[2*i+1][0][1] for i in range(len(new)//2)}

>>> res
{'n1': 'v1', 'n2': 'v2', 'n3': 'v3'}

Try this:

new = [[('name', 'n1')], [('value', 'v1')], [('name', 'n2')], [('value', 'v2')], [('name', 'n3')], [('value', 'v3')]]
output = {}
while new:
    key = new.pop(0)
    value = new.pop(0)
    output[key[0][1]] = value[0][1]

print(output) 
# output: {'n1': 'v1', 'n2': 'v2', 'n3': 'v3'}
Related