我的Python代码中有一个元组结构,它声明了以下内容:
match_entry = (util.frozendict(rule_match), priority, version)
当我打印match_entry时,我看到以下内容:
print match_entry
({'switch': 1, 'dstmac': 00:00:00:00:00:01, 'srcmac': 00:00:00:00:00:01}, 60000, 5)
我正在寻找这个元组的元组字母,让我们称之为dict_of_tuples; dict的相应输出如下。
print dict_of_tuples
{({'switch': 5, 'dstmac': '00:00:00:00:00:00', 'srcmac': '00:00:00:00:00:01'}, 59999, 7): [CountBucket 140271056467472, CountBucket 140271056411280], ({'switch': 5, 'dstmac': '00:00:00:00:00:00', 'srcmac': '00:00:00:00:00:01'}, 59999, 5): [CountBucket 140271056467472, CountBucket 140271056411280], ({'switch': 1, 'dstmac': '00:00:00:00:00:01', 'srcmac': '00:00:00:00:00:01'}, 60000, 5): [CountBucket 140271057099664, CountBucket 140271056501008]}
但是,当我检查匹配条目是否在元组中时:
if match_entry in dict_of_tuples:
我没有看到任何结果,即使match_entry明显在dict_of_tuple中。有这种情况的原因是什么?
答案 0 :(得分:0)
字典不可删除,所以我认为你的结构可能不可能:
>>> {({1:2, 2:3}, 2, 3): [1,2,3]}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'
词典不允许在其键中存在dict。所以要确保它真的不像字符串那样。
修改强>:
作为评论中的mentioned,冻结字典(不可变字典)将是可散列的,因此可以解决此问题。但是你必须修改默认的dict类型。通常,您可以在运行时修改dict:
d = {}
d["key"] = "val"
已在Object
中使用__setattr__启用了该功能。当我们需要不可变类?基本上,不可变对象在内存上更有效。以下是a topic。
答案 1 :(得分:0)
import frozendict as util
from collections import defaultdict
### Create the first entry using hashable frozendict
match = util.frozendict({'switch': 1, 'dstmac': '00:00:00:00:00:01', 'srcmac': '00:00:00:00:00:01'})
match_array = tuple[match,60000,5]
count_bucket2 = dict(CountBucket1 = 140271057099664, CountBucket2 = 140271056501008)
### Create the second entry using hashable frozendict
match_entry = util.frozendict(switch= 5, dstmac= '00:00:00:00:00:00', srcmac= '00:00:00:00:00:01')
match_array1 = tuple([match_entry, 59999, 7])
count_bucket1 = dict(CountBucket1 = 140271056467472, CountBucket2 = 140271056411280)
# Initialize the dictionary of tuples
dict_of_tuples = ({tuple(match_array) : count_bucket2},{tuple(match_array1) : count_bucket1})
####### Your match entry
match_entry = [{'switch': 1, 'dstmac': '00:00:00:00:00:01', 'srcmac': '00:00:00:00:00:01'},60000,5]
#Treating the final structure as a tuple. Each element of the tuple is a #dictionary.
k = 0
while k < len(dict_of_tuples):
key = dict_of_tuples[k].iterkeys()
val = dict_of_tuples[k].itervalues()
if key.next() == tuple(match_entry):
print ('Has key','corresponding value',val.next())
else:
print "Key not present"
k+= 1