Python Tuple to Dict, with additional list of keys
Asked Answered
C

2

14

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,
}]
Charcoal answered 12/12, 2013 at 10:25 Comment(2)
And what have you tried?Owsley
@LutzHorn so far nothing, but my only plan of attack at this point is to loop through the list, pull all elements of the list into 5 different variables, then add those 5 variables into a dict and push that to the new list. So I wouldn't really be making use of the keys list at all. This method seems very cumbersome to me though, so I thought there must be a cleaner way.Charcoal
A
38
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.

Acrobat answered 12/12, 2013 at 10:29 Comment(1)
Short & sweet, and uses a nice list comprehension.Donaghue
O
3
import json

ts = [(u'030944', u'20091123', 10, 30, 0), (u'030944', u'20100226', 10, 15, 0)]
fs = ['id', 'date', 'hour', 'minute', 'interval']
us = []

for t in ts:
    us.append(dict(zip(fs, t)))

print(json.dumps(us))

Result:

[
    {
        "date": "20091123",
        "interval": 0,
        "minute": 30,
        "id": "030944",
        "hour": 10
    },
    {
        "date": "20100226",
        "interval": 0,
        "minute": 15,
        "id": "030944",
        "hour": 10
    }
]
Owsley answered 12/12, 2013 at 10:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.