简体   繁体   中英

How to update a key in a dictionary without overwriting the old value

input = { "a" : { "x": 1, "y": 2 },
     "b" : { "x": 3, "z": 4 } }
output = {'y': {'a': 2},
                'x': {'a': 1, 'b': 3},
                'z': {'b': 4} }

I need to make a new dictionary given the input and it should come out as the output. So far I have written:

def pivot_nested_dict(nested_dict):
5       stateDict={}
6       for i in nested_dict:
7           dict2=nested_dict[i]
8           for j in dict2:
9               stateDict[j]= {i: dict2[j]}
10      return stateDict
11  
12  print pivot_nested_dict(input)

I almost have the answer, output={'y': {'a': 2}, 'x': {'b': 3}, 'z': {'b': 4}}. So, the x key is overwriting the 'a': 1. How do I keep both the a and the b?

Short of duplicating the dictionary, there is no way to retain the original value on a dictionary once you change the value that corresponds to the given key.

For example, the below overwriting will always happen no matter how complex the data structure.

x = {'a':1}
x['a'] = 2
print x
>>> {'a': 2}

You can duplicate it, but the original value will need to be managed manually.

x = {'a':1}
x,oldx = x,x.copy()
oldx['a'] = 2
print x, oldx
>>> {'a': 2} {'a': 1}

You could take advantage of the fact that values can be any type of structure including arrays or dictionaries, to store each successive change of value.

What you need to this is check if the key is already in stateDict , if it is, then add a new element to the nested dictionary:

def pivot_nested_dict(nested_dict):
    stateDict = {}
    for i in nested_dict:
        dict2 = nested_dict[i]
        for j in dict2:
            if j not in stateDict:
                stateDict[j] = {i: dict2[j]}
            else:
                stateDict[j][i] = dict2[j]
    return stateDict

print pivot_nested_dict(inp)

I ve got this little script yo get your job done.
NOTE : Provided the input is correct.

code:

output = {}
for d in input.items():
    for item in d:
        if type(item) == dict:
            for i in item.keys():
                d = {k:item[i]}
                output[i] = {k:item[i]} if not i in output.keys() else dict(output[i].items() + d.items())
        else: k=item  

input:

input = { "a" : { "x": 1, "y": 2 ,'z':15},"b" : { "x": 3, "z": 4 } }

output:

{'y': {'a': 2}, 'x': {'a': 1, 'b': 3}, 'z': {'a': 15, 'b': 4}}  

Hope this helps :)

I have this one

input = { "a" : { "x": 1, "y": 2 },
     "b" : { "x": 3, "z": 4 } }

output = {}

for k,v in zip(input.keys(), input.values()):
    for kk, vv in zip(v.keys(), v.values()):
        if kk in output.keys():
            output[kk][k] = vv
        else:
            output[kk] = {k : vv}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM