我想創建一個由字典鍵組成的列表,但這些字典嵌套在列表中。例如,給定下面的JSON:從嵌套字典創建列表
{
"test_cases": [{
"name": "first request",
"request": {
"url": "{{env_base_url}}/v2/597649d3110000be08b1be84/{{env_userName}}"
},
"variables": {
"var1": "some stuff",
"var2": "some other stuff"
}
},
{
"name": "second request",
"request": {
"url": "{{env_base_url}}/v2/597649d3110000be08b1be84/{{env_userName}}"
},
"variables": {
"var3": "some new stuff",
"var4": "some other new stuff"
}
}
]
}
我想創造一切從每個test_case的變量鍵的列表 - 示例輸出將是:
list = ['var1', 'var2', 'var3', 'var4]
我有實現這個代碼,但似乎過於複雜...
test_var_names = [list(test['variables'].keys()) for test in data['test_cases']]
i =0
while i < len(test_var_names):
test_var_name = test_var_names[i]
if isinstance(test_var_name, list):
for item in test_var_name:
test_var_names.append(item)
test_var_names.remove(test_var_name)
i = i-1
i += 1
print (test_var_names)
什麼是while循環的功能是什麼?這似乎是第一行應該做的工作 – TallChuck