Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python converting the values from dicts into a tuples

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?

like image 331
chrism Avatar asked Jul 08 '10 09:07

chrism


People also ask

How do you convert to tuple in Python?

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.

How do you turn a list into a tuple?

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.

Can a Python dictionary value be a tuple?

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).

Can the key of a dictionary be a tuple?

A tuple can never be used as a key in a dictionary.


1 Answers

>>> l = [{'id':1,'name':'Foo'},{'id':2,'name':'Bar'}]
>>> [tuple(d.values()) for d in l]
[(1, 'Foo'), (2, 'Bar')]
like image 104
SilentGhost Avatar answered Oct 01 '22 11:10

SilentGhost