Python列表中的元组转换为字典

2024-04-26 09:48:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我的数据格式如下:

例如

[('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}]

什么是语法上最干净的方式来实现这一点?你知道吗


Tags: 数据格式方式语法year数据格式value1value2
3条回答
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)

这里有一个想法,分两个步骤:

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

试试这个:

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

相关问题 更多 >