gpt4 book ai didi

python - 如果字典的键位于卡住集中,则检索值

转载 作者:行者123 更新时间:2023-11-30 23:13:11 24 4
gpt4 key购买 nike

我使用 freezesets 来保存字典的键,以利用并集、差集和交集运算。但是当我尝试通过 dict.get() 从字典中按键检索值时,它会产生 None 值。

newDict = {'a': 1, 'b': 2, 'c': 3, 'd': True}
stKeys = set(newDict)
stA = frozenset('a')
stB = frozenset('b')
stC = frozenset('c')
stD = frozenset('d')

print(stKeys)
print(newDict.get(stA & stKeys))
print(newDict.get(stB & stKeys))
print(newDict.get(stC & stKeys))
print(newDict.get(stD & stKeys))

产生:

>>>None
>>>None
>>>None
>>>None

甚至:

print(newDict.get(stA))
print(newDict.get(stB))
print(newDict.get(stC))
print(newDict.get(stD))

产生:

>>>None
>>>None
>>>None
>>>None

如果您的键位于卡住集中,如何从字典中检索值?

Thanks to Martijn Pieters! The answer is DVO (Dictionary view objects) and the generator expression if you want to add the result to a list()

最佳答案

您可以使用dictionary view objects如果你想寻找设置的交集:

for key in newDict.viewkeys() & stA:
# all keys that are in the intersection of stA and the dictionary

在Python 3中,默认返回字典 View ;您可以在此处使用 newDict.keys() :

for key in newDict.keys() & stA:
# all keys that are in the intersection of stA and the dictionary

Python 3 演示:

>>> newDict = {'a': 1, 'b': 2, 'c': 3, 'd': True}
>>> stA = frozenset('a')
>>> stB = frozenset('b')
>>> stC = frozenset('c')
>>> stD = frozenset('d')
>>> newDict.keys() & stA
{'a'}
>>> for key in newDict.keys() & stA:
... print(newDict[key])
...
1

关于python - 如果字典的键位于卡住集中,则检索值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29459097/

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