python - 如何在不覆盖旧值的情况下更新字典中的键

标签 python dictionary

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

我需要根据输入创建一个新字典,它应该作为输出出现。到目前为止我已经写了:

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)

我几乎有了答案,output={'y': {'a': 2}, 'x': {'b': 3}, 'z': {'b': 4}}。 所以,x 键覆盖了 'a': 1. 如何同时保留 a 和 b?

最佳答案

你需要做的是检查键是否已经在 stateDict 中,如果是,则向嵌套字典中添加一个新元素:

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)

关于python - 如何在不覆盖旧值的情况下更新字典中的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19993841/

相关文章:

ios - 如何将字典值传递给数组?

dictionary - 如何在 clojure 中获取映射的嵌套键?

python - 使用字典更新 Pandas 数据框或 csv

python - 使用python将arduino中的字符串存储到文本文件

python - 如何在 Python 中过滤掉字典中的非字符串键?

python - 在 Python 中按排序顺序从排序的迭代器中产生?

python - 使用 pyplot 返回复数值的绘图函数

python - 从字典列表中返回最大的字典和

python - 谷歌合作实验室: How can i mount two google drive accounts?

Python:如何修复我的代码以便追加将参数添加到列表中?