Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Tuple to Dict, with additional list of keys

So I have this array of tuples:

[(u'030944', u'20091123', 10, 30, 0), (u'030944', u'20100226', 10, 15, 0)]

And I have this list of field names:

['id', 'date', 'hour', 'minute', 'interval']

I would like to, in one fell swoop if possible, to convert the list of tuples to a dict:

[{
    'id': u'030944',
    'date': u'20091123',
    'hour': 10,
    'min': 30,
    'interval': 0,
},{
    'id': u'030944',
    'date': u'20100226',
    'hour': 10,
    'min': 15,
    'interval': 0,
}]
like image 639
DanH Avatar asked Dec 12 '13 10:12

DanH


People also ask

Can a tuple with a list be a key in a dictionary?

A tuple containing a list cannot be used as a key in a dictionary. Answer: True. A list is mutable. Therefore, a tuple containing a list cannot be used as a key in a dictionary.

How do I convert a tuple to a dictionary in Python?

In Python, use the dict() function to convert a tuple to a dictionary. A dictionary object can be created with the dict() function. The dictionary is returned by the dict() method, which takes a tuple of tuples as an argument.

How do you create a dictionary from a list of tuples?

Use a dict comprehension to convert a list of tuples to a dictionary, e.g. my_dict = {tup[0]: tup[1] for tup in list_of_tuples} . The dict comprehension will iterate over the list allowing us to set each key-value pair to specific tuple elements. Copied!


1 Answers

data = [(u'030944', u'20091123', 10, 30, 0), (u'030944', u'20100226', 10, 15, 0)]
fields = ['id', 'date', 'hour', 'minute', 'interval']
dicts = [dict(zip(fields, d)) for d in data]

To explain, zip takes one or more sequences, and returns a sequence of tuples, with the first element of each input sequence, the second, etc. The dict constructor takes a sequence of key/value tuples and constructs a dictionary object. So in this case, we iterate through the data list, zipping up each tuple of values with the fixed list of keys, and creating a dictionary from the resulting list of key/value pairs.

like image 150
Martin O'Leary Avatar answered Oct 22 '22 03:10

Martin O'Leary