J.Do
J.Do

Reputation: 428

How to transform a list of dicts into a list of tuples?

I have a list of dictionaries like this:

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 transform the above list into? (*):

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

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

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

However, I was not able to extract the second element position of the list of dictionaries into a list of tuples, as (*)

Upvotes: 6

Views: 174

Answers (2)

cs95
cs95

Reputation: 402363

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

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

In the lambda function, specify that you wish to create a tuple out of the dict values. This can also be sped up using a vanilla function, instead of 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. The other answer has already provided the solution for this.

Alternatively, as a fix to your existing solution, you just need to replace .items() with .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')
]

Note that in all of these solutions, there is no guaranteed order of the generated tuples.


Timings

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

Upvotes: 7

Mohd
Mohd

Reputation: 5613

What you need is .values() and not .items() for example (using list-comprehension):

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

output:

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

Upvotes: 5

Related Questions