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

2024-04-24 14:04:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一本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的差异大于1。但是我不知道怎么解决这个问题。你知道吗


Tags: 方法keyintestfor字典iscounter
2条回答

你可以这样使用字典理解:

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

您可以通过嵌套的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}

相关问题 更多 >