I have a list of dictionaries that looks like this:
[{'id':1,'name':'Foo'},{'id':2,'name':'Bar'}]
I'd like to convert the values from each dict into a list of tuples like this:
[(1,'Foo'),(2,'Bar')]
How can I do this?
1) Using tuple() builtin function tuple () function can take any iterable as an argument and convert it into a tuple object. As you wish to convert a python list to a tuple, you can pass the entire list as a parameter within the tuple() function, and it will return the tuple data type as an output.
Using the tuple() built-in function An iterable can be passed as an input to the tuple () function, which will convert it to a tuple object. If you want to convert a Python list to a tuple, you can use the tuple() function to pass the full list as an argument, and it will return the tuple data type as an output.
Python Dictionaries Python dictionary is a collection which is unordered, changeable and indexed. Each item of a dictionary has a key:value pair and are written within curly brackets separated by commas. The values can repeat, but the keys must be unique and must be of immutable type(string, number or tuple).
A tuple can never be used as a key in a dictionary.
>>> l = [{'id':1,'name':'Foo'},{'id':2,'name':'Bar'}]
>>> [tuple(d.values()) for d in l]
[(1, 'Foo'), (2, 'Bar')]
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