如果字典的键在冻结集中,则检索值

Retrieving values if keys of the dictionary are in frozensets

我正在使用 frozensets 来保留我的字典的键,以利用并集、差集和交集操作。但是当我试图通过 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

如果您的键在 frozensets 中,如何从字典中检索值?

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()

要创建冻结集密钥,您需要实际创建冻结集并将它们用作密钥:

newDict = {
    frozenset('a'): 1,
    frozenset('b'): 2,
    frozenset('c'): 3,
    frozenset('d'): True
}

测试:

>>> {frozenset('a'):1}[frozenset('a')]
1

如果你想寻找set intersections:

,你可以使用dictionary view objects
for key in newDict.viewkeys() & stA:
    # all keys that are in the intersection of stA and the dictionary

在Python3中,默认返回字典视图;你可以在这里使用 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

你实际上可以做你想做的事,至少在 3.6.1 中,我怀疑是 2。7.x 还有:

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

print(newDict[stA])
print(newDict[stB])
print(newDict[stC])
print(newDict[stD])

输出:

frozenset({'a'})
1
2
3
True

问题似乎是键被指定为字符串对象而不是 frozenset,但搜索设置为查找 frozenset。