[英]python list of tuples to a dictionary
我有一个看起来像这样的数据格式:
例如,
[('2011', 1, 'value1', '68843'),
('2011', 1, 'value2', '37029'),
('2014', 1, 'value1', '66061'),
('2014', 1, 'value2', '96994'),
('2016', 1, 'value1', '68286'),
('2016', 1, 'value2', '84507'),
('2011', 1, 'value3', '58882')]
我想使用python将此数据转换为以下格式
[{"year":2011,"value1":68843,"value2":37029,"value3":58882},
{"year":2014,"value1":66061,"value2":96994},
{"year":2016,"value1":68286,"value2":84507}]
语法上最干净的方法是什么?
import collections
values = [
('2011', 1, 'value1', '68843'),
('2011', 1, 'value2', '37029'),
('2014', 1, 'value1', '66061'),
('2014', 1, 'value2', '96994'),
('2016', 1, 'value1', '68286'),
('2016', 1, 'value2', '84507'),
('2011', 1, 'value3', '58882')
]
d = collections.defaultdict(dict)
for year, _, name, value in values:
d[year][name] = value
result = [{'year': year, **values} for year, values in d.items()]
print(result)
尝试这个 :
a = [('2011', 1, 'value1', '68843'), ('2011', 1, 'value2', '37029'), ('2014', 1, 'value1', '66061'), ('2014', 1, 'value2', '96994'), ('2016', 1, 'value1', '68286'), ('2016', 1, 'value2', '84507'), ('2011', 1, 'value3', '58882')]
c =[]
for i in set([k[0] for k in a]):
temp = {}
temp['year'] =i
for j in a:
if j[0]==i:
temp[j[2]] = int(j[-1])
c.append(temp)
输出 :
[{'year': '2011', 'value1': 68843, 'value2': 37029, 'value3': 58882}, {'year': '2014', 'value1': 66061, 'value2': 96994}, {'year': '2016', 'value1': 68286, 'value2': 84507}]
这是一个想法,分两步进行:
from collections import defaultdict
ts = [('2011', 1, 'value1', '68843'), ('2011', 1, 'value2', '37029'),
('2014', 1, 'value1', '66061'), ('2014', 1, 'value2', '96994'),
('2016', 1, 'value1', '68286'), ('2016', 1, 'value2', '84507'),
('2011', 1, 'value3', '58882')]
# first, collect the data corresponding to a single year
d = defaultdict(list)
for year, _, val, num in ts:
d[year].append((val, num))
# second, consolidate it in a list
[dict([['year', year]] + vals) for year, vals in d.items()]
=> [{'value2': '96994', 'value1': '66061', 'year': '2014'},
{'value2': '84507', 'value1': '68286', 'year': '2016'},
{'value3': '58882', 'value2': '37029', 'value1': '68843', 'year': '2011'}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.