简体   繁体   English

Python Tuple to Dict,带有额外的键列表

[英]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: 我想,如果可能的话,一举将元组列表转换为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,
}]
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. 为了解释, zip接受一个或多个序列,并返回一个元组序列,每个输入序列的第一个元素,第二个元素等dict构造函数接受一系列键/值元组并构造一个字典对象。 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. 因此,在这种情况下,我们遍历数据列表,使用固定的键列表来压缩每个元组值,并从结果的键/值对列表中创建字典。

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
    }
]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM