gpt4 book ai didi

python - 为什么这本字典会变成一个元组?

转载 作者:行者123 更新时间:2023-12-05 09:06:07 25 4
gpt4 key购买 nike

我有一个复杂的字典:

l = {10: [{'a':1, 'T':'y'}, {'a':2, 'T':'n'}], 20: [{'a':3,'T':'n'}]}

当我尝试遍历字典时,我没有得到一个包含值列表的字典,而我得到的是一个像这样的元组:

for m in l.items():
print(m)

(10, [{'a': 1, 'T': 'y'}, {'a': 2, 'T': 'n'}])
(20, [{'a': 3, 'T': 'n'}])

但是当我打印 l 时,我得到了我原来的字典:

In [7]: l
Out[7]: {10: [{'a': 1, 'T': 'y'}, {'a': 2, 'T': 'n'}], 20: [{'a': 3, 'T': 'n'}]}

如何遍历字典?我仍然需要键并处理值列表中的每个字典。

最佳答案

这里有两个问题。首先,您问为什么将其变成“元组”——这个问题的答案是因为这是字典上的 .items() 方法返回的内容——每个键/值对的元组。

知道了这一点,您就可以决定如何使用这些信息。您可以选择在迭代期间将元组扩展为两部分

for k, v in l.items():
# Now k has the value of the key and v is the value
# So you can either use the value directly
print(v[0]);
# or access using the key
value = l[k];
print(value[0]);
# Both yield the same value



关于python - 为什么这本字典会变成一个元组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66343171/

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