Python converts values ​​from dicts to tuples

I have a list of dictionaries that look like this:

[{'id':1,'name':'Foo'},{'id':2,'name':'Bar'}] 

I would like to convert the values ​​from each dict to a list of tuples like this:

 [(1,'Foo'),(2,'Bar')] 

How can i do this?

+4
source share
3 answers
 >>> l = [{'id':1,'name':'Foo'},{'id':2,'name':'Bar'}] >>> [tuple(d.values()) for d in l] [(1, 'Foo'), (2, 'Bar')] 
+15
source

Note that the approach in SilentGhost's answer does not guarantee the order of each tuple, since dictionaries and their values() do not have a built-in order. So you can just get ('Foo', 1) as (1, 'Foo') , in the general case.

If this is unacceptable and you definitely need an id , you will have to do this explicitly:

 [(d['id'], d['name']) for d in l] 
+10
source

This will convert the dictionary to a tuple always in a specific order

d = {'x': 1 , 'y':2} order = ['y','x'] tuple([d[field] for field in order])

0
source

Source: https://habr.com/ru/post/1315042/


All Articles