我使用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中,如何从字典中检索值?
感谢 Martijn Pieters !答案是DVO(字典视图 对象)和生成器表达式,如果要添加结果 列表()
答案 0 :(得分:2)
如果您想查找设置交叉点,可以使用dictionary view objects:
for key in newDict.viewkeys() & stA:
# all keys that are in the intersection of stA and the dictionary
在Python 3中,返回字典视图是默认的;你可以在这里使用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
答案 1 :(得分:1)
要创建冻结集密钥,您需要实际创建冻结集并将其用作密钥:
newDict = {
frozenset('a'): 1,
frozenset('b'): 2,
frozenset('c'): 3,
frozenset('d'): True
}
测试:
>>> {frozenset('a'):1}[frozenset('a')]
1
答案 2 :(得分:0)
你实际上可以做你想做的事情,至少在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
问题似乎是密钥被指定为字符串对象而不是冻结集,但搜索被设置为查找冻结集。