【发布时间】:2021-12-13 00:26:01
【问题描述】:
我有一本像 json 格式的字典。如下:-
dito1 ={'result2':[{'math':20,'science':22,'english':31},{'math':26,'science':27,'english':33},
{'math':15,'science':55,'english':44}],'pet2':0,
'result':[{'rt':66,'io':49,'op':10},{'rt':24,'io':25,'op':5}],'pet':20}
现在我想使用上述值创建一个新字典,新字典必须如下所示:-
{'type': 'etc', 'scores': [{'math': 20, 'science': 22, 'english': 31}, {'math': 26, 'science': 27, 'english': 33}, {'math': 15, 'science': 55, 'english': 44}], 'math total': 61,'scores2':[{'math': 66, 'science': 49, 'english': 10}, {'math': 24, 'science': 25, 'english': 5}],'math total':90}
在第一个字典中有两个键 result2,result 具有列表的分数信息。通过使用此信息,它们必须按上述方式进行转换,第二个词典中的数学总分是每个列表中数学的总分。我试图获得所需的输出,但我无法根据它们所属的键将它们分成两部分。我试过的代码如下:-
dito1 ={'result2':[{'math':20,'science':22,'english':31},{'math':26,'science':27,'english':33},
{'math':15,'science':55,'english':44}],'pet2':0,
'result':[{'rt':66,'io':49,'op':10},{'rt':24,'io':25,'op':5}],'pet':20}
reslt=[]
math_total=[]
for key,value in dito1.items():
if key == 'result' or key == 'result2':
for i in value:
for k,v in i.items():
if k == 'math':
t=v
if k == 'rt':
t=v
if k == 'science':
r=v
if k == 'io':
r=v
if k=='op':
e=v
if k=='english':
e=v
rest ={'math':t,'science':r,'english':e}
math_total.append(t)
reslt.append(rest)
final_dict={'type':'etc','math total':reslt,'scores':sum(math_total)}
print(final_dict)
我得到的输出是:-
{'type': 'etc', 'scores': [{'math': 20, 'science': 22, 'english': 31}, {'math': 26, 'science': 27, 'english': 33}, {'math': 15, 'science': 55, 'english': 44}, {'math': 66, 'science': 49, 'english': 10}, {'math': 24, 'science': 25, 'english': 5}], 'math total': 151}
异常输出:-
{'type': 'etc', 'scores': [{'math': 20, 'science': 22, 'english': 31}, {'math': 26, 'science': 27, 'english': 33}, {'math': 15, 'science': 55, 'english': 44}], 'math total': 61,'scores2':[{'math': 66, 'science': 49, 'english': 10}, {'math': 24, 'science': 25, 'english': 5}],'math total2':90}
【问题讨论】:
-
您能检查/确认您预期输出中的键吗?它有两次密钥
'math total'。 -
我认为这是设计使然。他想计算两个字典的
math_total -
@pyzer 是的。我要计算
-
@JoshuaVoskamp 抱歉忘记为密钥添加新名称
标签: python json list dictionary