How to convert a list of dicts to a list of tuples?

I have a list of such dictionaries:

l = [{'pet': 'cat', 'price': '39.99', 'available': 'True'}, 
{'pet': 'cat', 'price': '67.99', 'available': 'True'}, 
{'pet': 'dog', 'price': '67.00', 'available': 'False'}
,....,
{'pet': 'fish', 'price': '11.28', 'available': 'True'}]

How can I convert the above list? (*):

l_2 = [('cat','39.99','True'),('cat','67.99','True'),('dog','67.00','False'),....,('fish','11.28','True')]

I tried using .items()and l[1]:

for l in new_list:
        new_lis.append(l.items())

However, I was not able to extract the second position of the dictionary list item into the tuple list, since (*)

+4
source share
2 answers

Option 1
Use map(short and sweet, but slow):

l_2 = list(map(lambda x: tuple(x.values()), l))

In the function, lambdaspecify that you want to create a tuple of values dict. This can also be accelerated by using the vanilla function instead lambda:

def foo(x): 
     return tuple(x.values())

l_2 = list(map(foo, l))

print(l_2)
[
    ('39.99', 'cat', 'True'),
    ('67.99', 'cat', 'True'),
    ('67.00', 'dog', 'False'),
    ('11.28', 'fish', 'True')
]

Option 2
Use a list comprehension. Another answer has already given a solution for this.

, .items() .values():

new_list = []
for x in l:
     new_list.append(tuple(x.values()))

print(new_list)
[
    ('39.99', 'cat', 'True'),
    ('67.99', 'cat', 'True'),
    ('67.00', 'dog', 'False'),
    ('11.28', 'fish', 'True')
]

, .


Solution 1 (improved):   100000 loops, best of 3: 2.47 µs per loop 
Solution 2:             1000000 loops, best of 3: 1.79 µs per loop
Your solution:           100000 loops, best of 3: 2.03 µs per loop
+5

, , .values(), .items() ( list-comprehension):

l_2 = [tuple(x.values()) for x in l]

:

[('cat', 'True', '39.99'), ('cat', 'True', '67.99'), ('dog', 'False', '67.00'), ('fish', 'True', '11.28')]
+4

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


All Articles