Stephan K.
Stephan K.

Reputation: 15712

Python Transform Key Value into new form

I have:

['key',{'key1':val1, 'key2':val2, 'key3':val3}] 

how to arrive at:

[('key1','key'), ('key2','key'), ('key3','key')]

I would use list comprehension but I am ook here.

This is what I have so far:

[(k,j) for (k,v) in (j,(k,v))]

Upvotes: 0

Views: 41

Answers (2)

Padraic Cunningham
Padraic Cunningham

Reputation: 180441

Using zip and itertools:

l = ['key',{'key1':"val1", 'key2':"val2", 'key3':"val3"}]

from itertools import repeat

print(list(zip(l[1],repeat(l[0]))))
[('key3', 'key'), ('key2', 'key'), ('key1', 'key')]

Upvotes: 0

Reut Sharabani
Reut Sharabani

Reputation: 31339

Try this:

lst = ['key',{'key1':val1, 'key2':val2, 'key3':val3}]
[(other_key, lst[0]) for other_key in lst[1]]

Not that order is not promised as dict is not ordered, so consider using sorted.

Upvotes: 1

Related Questions