使用python枚举其中包含字典的列表

时间:2016-11-03 01:18:00

标签: python json

我有一个看起来像这样的结构:

{ 
"permutations": [
     {
        "testname": "Test1",
        "file_type": "file1",
        "test_options": {
            "rule_entities": [
                "name1"
         ],
        },
        ],
        "userType": "user",
        "rulename": "rule1",
        "action": "alert",
      },
     {
        "testname": "Test2",
        "file_type": "file2",
        "test_options": {
            "rule_entities": [
                "name2"
            ],
        },
        ],
        "userType": "user",
        "rulename": "rule2",
        "action": "alert",
      }
}

我想在上面的结构testname和rulename中进行更改,方法是使用rule_entities值附加变量,使testname:“Test1_name1”和rulename:“rule1_name1”,其中name1来自rule_entities数组。因此,上述结构应该是最终结构

{ 
"permutations": [
     {
        "testname": "Test1_name1",
        "file_type": "file1",
        "test_options": {
            "rule_entities": [
                "name1"
         ],
        },
        ],
        "userType": "user",
        "rulename": "rule1_name1",
        "action": "alert",
      },
     {
        "testname": "Test2_name2",
        "file_type": "file2",
        "test_options": {
            "rule_entities": [
                "name2"
            ],
        },
        ],
        "userType": "user",
        "rulename": "rule2_name2",
        "action": "alert",
      }
}

我使用以下代码snipet尝试了一下

for index, d in enumerate['permutations']:
    testname = d['permutations'][index]['testname']
    testname_new = testname + '_' + rule_entitities


for index, d in enumerate['permutations']:
    rulename = d['permutations'][index]['rulename']
    rulename_new = rulename + '_' + rule_entities

我没有得到所需的输出。在此先感谢!!

2 个答案:

答案 0 :(得分:1)

您从未更新存储在词典中的值

for index, d in enumerate['permutations']:
    testname = d['permutations'][index]['testname']
    testname_new = testname + '_' + rule_entities
    d['permutations'][index]['testname'] = testname_new


for index, d in enumerate['permutations']:
    rulename = d['permutations'][index]['rulename']
    rulename_new = rulename + '_' + rule_entities
    d['permutations'][index]['rulename'] = rulename_new

答案 1 :(得分:0)

我使用以下代码完成了工作:

NotificationCenter.default.post(name: NSNotification.Name(rawValue: "showVideoRewardAd"), object: nil)

由于