我需要使用 item.replace(" ", "_").lower() 更改字典中鍵的名稱 我怎樣才能訪問這些鍵?
{
"environment": [
{
"Branch Branching": "97/97(100%)",
"Test Status": "TC39",
},
{
"Branch Branching": "36/36(100%)",
"Test Status": "TC29",
}
],
}
uj5u.com熱心網友回復:
一種方法是使用:
dictionary[new_key] = dictionary.pop(old_key)
在您的示例中:
env = {
"environment": [
{
"Branch Coverage": "97/97(100%)",
"Test Environment": "REGISTERHANDLING",
"Test Configuration": "TC39",
},
{
"Branch Coverage": "36/36(100%)",
"Test Environment": "PRA",
"Test Configuration": "TC29",
}
],
}
# Looping over each index in the env['environment'] list,
# this way we can edit the original dictionary.
# Note that enumerate returns a tuple of values (idx, val)
# And _ is commonly used to demonstrate that we will not be using val, only the index.
for index, _ in enumerate(env['environment']):
# For each key, we want to create a new key and delete the old one.
for key in env['environment'][index].keys():
# Calculate the new key
new_key = key.replace(" ", "_").lower()
# .pop deletes the old key and returns the result, and the left hand side of this operation creates the new key in the correct index.
env['environment'][index][new_key] = env['environment'][index].pop(key)
這個問題之前已經解決了,如果您想探索其他答案,請單擊此處。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/435531.html
標籤:Python json python-2.7 字典 嵌套的
上一篇:為每個n元素打開新檔案
