【问题标题】:python : update same dictionary keys at different index in a listpython:更新列表中不同索引处的相同字典键
【发布时间】:2020-03-01 13:39:51
【问题描述】:

我正在尝试使用 for 循环更新列表中不同索引处的相同字典键。 我不确定这是否是使用 python 代码执行此操作的允许格式/方式。任何帮助将不胜感激。

rc_description_final=["Apple","Orange", "Pineapple"]
rc_action_final = ["Red", "Fruit", "Yellow"]
k=0
while k < len(IDs):
    temp={}
    rc = {}
    temp['Rate'] = [rc]
    d = 0
    print(rc_description_final)
    print(len(rc_description_final))
    while d < len(rc_description_final):

        temp['Rate'][d]['Description'] = rc_description_final[d]

        temp['Rate'][d]['Action'] = rc_action_final[d]

        temp['Rate'].append(rc)

        d = d + 1
    json.dumps(temp)
    print(json.dumps(temp))
    k = k + 1

我希望输出为:

{
    "Rate Limits": [
      {
        "Description": "Apple",
        "Action": "Red"
      },
      {
        "Description": "Orange",
        "Action": "Fruit"
      },
      {
        "Description": "Pinapple",
        "Action": "Yellow"
      }
    ]
}

但我得到的输出是:

{
    "Rate Limits": [
    {
        "Description": "Pinapple",
        "Action": "Yellow"
     },
    {
        "Description": "Pinapple",
        "Action": "Yellow"
     },
    {
        "Description": "Pinapple",
        "Action": "Yellow"
     }
    ]
}

【问题讨论】:

    标签: json python-3.x dictionary


    【解决方案1】:

    在您的情况下,我在“temp['Rate'] = [rc]”处发现了问题。所以当 temp['Rate'] 改变时,rc 值会自动改变。这将引导您到此输出。

    这是我的代码供您参考:

    import json
    
    rc_description_final=["Apple","Orange", "Pineapple"]
    rc_action_final = ["Red", "Fruit", "Yellow"]
    k=0
    while k < 1:
      temp={}
      temp['Rate'] = []
      d = 0
      print(rc_description_final)
      print(len(rc_description_final))
      while d < len(rc_description_final):
        description_dict = {}
    
        description_dict['Description'] = rc_description_final[d]
        description_dict['Action'] = rc_action_final[d]
    
        temp['Rate'].append(description_dict)
    
        d = d + 1
    json.dumps(temp)
    print(json.dumps(temp))
    k = k + 1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-23
      • 2019-11-04
      • 1970-01-01
      • 1970-01-01
      • 2019-08-18
      • 1970-01-01
      • 1970-01-01
      • 2020-01-13
      相关资源
      最近更新 更多