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 (*)
To convert a list of lists to a list of tuples: Pass the tuple() class and the list of lists to the map() function. The map() function will pass each nested list to the tuple() class. The new list will only contain tuple objects.
A simple way to convert a list of lists to a list of tuples is to start with an empty list. Then iterate over each list in the nested list in a simple for loop, convert it to a tuple using the tuple() function, and append it to the list of tuples.
Use the list comprehension statement [list(x) for x in tuples] to convert each tuple in tuples to a list. This also works for a list of tuples with a varying number of elements.
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
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')]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With