首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >字典的Python列表.访问键

字典的Python列表.访问键
EN

Stack Overflow用户
提问于 2022-03-01 10:35:37
回答 1查看 48关注 0票数 0

我需要使用item.replace(“",”“).lower()更改字典中的键名,如何访问这些键?

代码语言:javascript
复制
{
  "environment": [
    {
      "Branch Branching": "97/97(100%)",
      "Test Status": "TC39",
    },
    {
      "Branch Branching": "36/36(100%)",
      "Test Status": "TC29",
    }
],
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-03-01 10:39:13

一种方法是使用:

代码语言:javascript
复制
dictionary[new_key] = dictionary.pop(old_key)

在你的例子中:

代码语言:javascript
复制
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)

这个问题已经解决了,如果您想探索其他的答案,click here.

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71307121

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档