Teh Ki
Teh Ki

Reputation: 455

Update key without affecting the key's values within a nested dictionary

I am trying to update a key while retaining its values within a nested dictionaries. While I have found a method to do so, I had to create new dictionaries in order to cater for it. As such, wondering if there anyone could provide me with a better insight on the approach I have taken?

init_dict = {
    'pageA' : {
        0 : {
            'menuA' : [
                'a01',
                'a02'
            ]
        }
    },
    'pageB' : {
        1 : {
            'menuB' : [
                'b10'
            ]
        }
    }
}

changed = {'pageB' : 0, 'pageA' : 1}

condense_dict = {}
for k, v in init_dict.items():
    for i in v.keys():
        condense_dict[k] = init_dict[k][i]


new_dict = {}
for i in condense_dict:
    new_dict[i] = {}
    new_dict[i][changed.get(i)] = condense_dict.get(i)

My expected output is as follows:

{
    'pageA' : {
        1 : {
            'menuA' : [
                'a01',
                'a02'
            ]
        }
    },
    'pageB' : {
        0 : {
            'menuB' : [
                'b10'
            ]
        }
    }
}

Upvotes: 1

Views: 75

Answers (3)

blhsing
blhsing

Reputation: 106553

You can pop the presumably only key from the sub-dict and assign it to the new key for each entry in changed:

for k, v in changed.items():
    init_dict[k][v] = init_dict[k].pop(next(iter(init_dict[k])))

init_dict becomes:

{'pageA': {1: {'menuA': ['a01', 'a02']}}, 'pageB': {0: {'menuB': ['b10']}}}

Upvotes: 2

Reedinationer
Reedinationer

Reputation: 5774

Using the .pop() method this can be done similar to this (although I'm sure you could rewrite it better)

init_dict = {
    'pageA': {
        0: {
            'menuA' : [
                'a01',
                'a02'
            ]
        }
    },
    'pageB': {
        1: {
            'menuB': [
                'b10'
            ]
        }
    }
}
print(init_dict)
thing = init_dict.pop('pageA')
sub_thing = thing.pop(0)
redone = {1: sub_thing}
init_dict.update({'pageA': redone})
print(init_dict)

{'pageA': {0: {'menuA': ['a01', 'a02']}}, 'pageB': {1: {'menuB': ['b10']}}}

{'pageA': {1: {'menuA': ['a01', 'a02']}}, 'pageB': {1: {'menuB': ['b10']}}}

You can see it's the same data as we start with, but we changed 0 to 1

Upvotes: 0

Aule Mahal
Aule Mahal

Reputation: 708

Here I use .pop() and change it inplace. With the same init_dict as you:

change_to = {1: 0, 0: 1}

for k, v in init_dict.items():
    for old_key in v.keys(): 
        if old_key in change_to:
            v[change_to[old_key]] = v.pop(old_key)

Upvotes: -1

Related Questions