How to replace dict keys preserving order

318 Views Asked by At
Envs = ["re","pr","qa"]
j = {'e.ticket.instructions': 'text', 'AGroup.ENV': 'text, loop','create.ENV.cro': 'boolean, loop'}
for env in Envs:
    j = {key.replace('ENV', env): j.pop(key) for key in j.keys()}
    for i in j:
        if "boolean" in j[i]:
            if env == "pr" and i == 'e.ticket.instructions':
                print "ignore"
            else:
                print "proceed"
           
            print(k)
        else
            print "not boolean"
    j = {key.replace(env, 'ENV'): j.pop(key) for key in j.keys()}

Expected Output: I should be able to replace env and iterate through keys and values in the dict but preserve the order as original order below.

j = {'e.ticket.instructions': 'text', 'AGroup.re': 'text, loop', 'create.pr.cr': 'boolean, loop'}

Also if env == "pr", it should ignore 'e.ticket.instructions' key, so the j should like below:

j = {'e.ticket.instructions': 'text', 'AGroup.pr': 'text, loop', 'create.pr.cr': 'boolean, loop'}

but its not preserving the order and changing it to below:

j = {'create.pr.cr': 'boolean, loop', 'AGroup.pr': 'text, loop', 'e.ticket.instructions': 'text'}
 

How to preservce the order while replacing the word in key.

1

There are 1 best solutions below

1
On

Well, dictionaries don't have guaranteed order until Python 3.6 (see PEP 468), so if you want that, you need to use collections.OrderedDict. This seems like a really complex method with popping keys and such. You could try this, but I can't tell what you're trying to do with the boolean / ticket.instructions skipping. for i in j checks only keys, of which none contain "boolean". And there are not keys or values that would match "ticket.instructions". Further you don't even change what is included in the dictionary with that as far as I can tell. It just does some prints.

Anyway, I hope this helps, or at least gets you started.

from collections import OrderedDict

envs = ["re", "pr", "qa"]
j = {
    "e.ticket.instructions": "text",
    "AGroup.ENV": "text, loop",
    "create.ENV.cro": "boolean, loop",
}

env_j = {
    env: {k.replace("ENV", env): v for k, v in OrderedDict(j).items()} for env in envs
}

print(env_j)

This outputs a dictionary like this:

{
    "re": {
        "e.ticket.instructions": "text",
        "AGroup.re": "text, loop",
        "create.re.cro": "boolean, loop",
    },
    "pr": {
        "e.ticket.instructions": "text",
        "AGroup.pr": "text, loop",
        "create.pr.cro": "boolean, loop",
    },
    "qa": {
        "e.ticket.instructions": "text",
        "AGroup.qa": "text, loop",
        "create.qa.cro": "boolean, loop",
    },
}