1

In python I have a dict as below :

{'name':{0:'tom',1:'dav'}, 'age':{0:22,1:23}}

I want change it to this:

[{'name':'tom','age':22}, {'name':'dav','age':23}]

Can you answer with the simplest way of doing this?

3 Answers 3

3

How about something like this?

>>> d = {'name':{0:'tom',1:'dav'}, 'age':{0:22,1:23}}
>>> values = zip(*[value.values() for value in d.values()])
>>> l = [{'name': name, 'age': age} for name, age in values]
>>> l
[{'name': 'tom', 'age': 22}, {'name': 'dav', 'age': 23}]

[value.values() for value in d.values()] return [['tom', 'dav'], [22, 23]] which's the values of your subdicts, and then, zip() return [('tom', 22), ('dav', 23)].

Then, we use for loop over the zipped values, and put the values into the dicts in l.

Sign up to request clarification or add additional context in comments.

Comments

0

Another variant in one line:

a = {'name':{0:'tom',1:'dav'}, 'age':{0:22,1:23}}
[ dict(zip(*(a.keys(),y))) for y in zip(*(x.values() for x in a.values())) ]

Comments

0

And Another one in one line ;)

age,name = {'name':{0:'tom',1:'dav'}, 'age':{0:22,1:23}}.values()
print [{'name': name[inx],'age':age[inx]} for inx in age]
[{'age': 22, 'name': 'tom'}, {'age': 23, 'name': 'dav'}]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.