Python Tuple到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:
[{
'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]
解释一下,zip
接受一个或多个序列,并返回一个元组序列,每个输入序列的第一个元素,第二个元素,等等.dict
构造函数接受键/值元组的序列,并构造一个字典对象.因此,在这种情况下,我们遍历数据列表,使用固定的键列表压缩每个值的元组,然后根据键/值对的结果列表创建字典.
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.
这篇关于Python Tuple到Dict,带有其他键列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!