gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 22:15:34 27 4
gpt4 key购买 nike

我在 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.但是我不知道如何解决这个问题。

最佳答案

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

关于python - 如何获取和修改嵌套字典的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50257201/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com