0

I need to change name of the keys in dictionary using item.replace(" ", "_").lower() How could I access these keys?

{
  "environment": [
    {
      "Branch Branching": "97/97(100%)",
      "Test Status": "TC39",
    },
    {
      "Branch Branching": "36/36(100%)",
      "Test Status": "TC29",
    }
],
}

1 Answer 1

0

One way is to use:

dictionary[new_key] = dictionary.pop(old_key)

In your example:

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)

This question was already solved before, if you'd like to explore other answers, click here.

3
  • I need to access keys Branch Coverage, Test Environment, Test Configuration. And by using for key in env["environment"].keys() I get this error:
    – user18292038
    Commented Mar 1, 2022 at 10:49
  • AttributeError: 'list' object has no attribute 'keys'
    – user18292038
    Commented Mar 1, 2022 at 10:49
  • @Irenaaa edited the answer accordingly. Please mark it as correct if it satisfies your question. Commented Mar 1, 2022 at 11:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.