【问题标题】:How to insert values into a nested dictionary from existing dictionary values如何从现有字典值将值插入嵌套字典
【发布时间】: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


【解决方案1】:

顺便说一句,我建议重新考虑这个final_dict 的结构/命名方案;使用 'scores''scores2' 之类的键表示您可能需要 list 结构而不是 dict 结构。

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}

translate = {'rt':'math','io':'science','op':'english'}

final_dict = {'type':'etc'}
for key,list_of_dict in dito1.items():
    if key in ['result', 'result2']:
        score_key = key.replace('result','scores')
        final_dict[score_key] = []

        math_total_key = key.replace('result','math_total')
        final_dict[math_total_key] = 0
        for d in list_of_dict:
            # translate to the intended score names as needed
            for k in ['rt','io','op']:
                if k in d:
                    d[translate[k]] = d.pop(k)

            # append the scores to the appropriate nested dict
            final_dict[score_key].append(dict(d))
            # and increment the math_total for that set of scores
            final_dict[math_total_key] += d['math']
print(final_dict)

结果

for key,value in final_dict.items():
    print(f'{key}: {value}')

# Output:
type: etc
scores2: [{'math': 20, 'science': 22, 'english': 31}, {'math': 26, 'science': 27, 'english': 33}, {'math': 15, 'science': 55, 'english': 44}]
math_total2: 61
scores: [{'math': 66, 'science': 49, 'english': 10}, {'math': 24, 'science': 25, 'english': 5}]
math_total: 90

【讨论】:

    猜你喜欢
    • 2019-11-27
    • 2014-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-17
    • 2020-07-09
    相关资源
    最近更新 更多