如何获取和修改嵌套字典的值?

时间:2018-05-09 15:38:32

标签: python dictionary

我在python中有这种字典:

x = {'test': {1: 2, 2: 4, 3: 5},
     'this': {1: 2, 2: 3, 7: 6},
     'is': {1: 2},
     'something': {90: 2,92:3}}

我想用我想要的任何值来修改键中的所有值。让我们说100,我尝试的方法如下:

counter = 1
print(x)
for key,anotherKey in x.items():
    while counter not in x[key]:
        counter+=1
    while counter in x[key]:
        x[key][counter] = 100
        counter+=1
    counter =0

结果如下:

{'test': {1: 100, 2: 100, 3: 100},
 'this': {1: 100, 2: 100, 7: 6},
 'is': {1: 100},
 'something': {90: 100,92: 3}}

我知道为什么会发生这种情况,因为循环没有考虑差异是否大于1,在这种情况下是'this':其中2到7之间的差异更大然而,我不知道如何解决这个问题。

2 个答案:

答案 0 :(得分:4)

您可以通过嵌套的for循环进行迭代:

x = {'test': {1: 2, 2: 4, 3: 5},
     'this': {1: 2, 2: 3, 7: 6},
     'is': {1: 2},
     'something': {90: 2,92:3}}

for a in x:
    for b in x[a]:
         x[a][b] = 100

print(x)

{'is': {1: 100},
 'something': {90: 100, 92: 100},
 'test': {1: 100, 2: 100, 3: 100},
 'this': {1: 100, 2: 100, 7: 100}}

或者对于新词典,您可以使用词典理解:

res = {a: {b: 100 for b in x[a]} for a in x}

答案 1 :(得分:-1)

您可以这样使用词典理解:

{a: {b:100 for b in d} for (a,d) in x.items()}