python3将字典元素嵌套到主字典

时间:2020-06-09 03:08:09

标签: python python-3.x dictionary

"a": "a",
"b": "b",
"c and d": {
               "c": "c",
               "d": "d"
           }

如何在python3中将其转换为以下字典?

"a": "a",
"b": "b",
"c": "c",
"d": "d"

谢谢!

2 个答案:

答案 0 :(得分:0)

尝试一下:

# New squeaky clean dict
new = {}
for k, v in old.items():    # Cycle through each key (k) and value (v)
    if 'and' in k:    # If there is the word 'and' - append the first (0) and last (-1) of the dict
        new[k[0]] = old[k][k[0]]
        new[k[-1]] = old[k][k[-1]]
    else:    # Otherwise just add the old value
        new[k] = v

print(old)
print(new)

输出:

{'a': 'a', 'b': 'b', 'c and d': {'c': 'c', 'd': 'd'}}

{'a': 'a', 'b': 'b', 'c': 'c', 'd': 'd'}

答案 1 :(得分:0)

这可能是最简单的解决方法。

a = {
    "a": "a",
    "b": "b",
    "c and d": {
                "c": "c",
                "d": "d"
            }
}

s = {}
def Merge(dict1, dict2): 
    return(dict2.update(dict1)) 

for key, value in a.items():
    if(type(value) is dict):
        Merge(value, s)
    else:
        Merge({key:value}, s)
print(s)

结果:

{'a': 'a', 'b': 'b', 'c': 'c', 'd': 'd'}
相关问题