[英]Searching key/values with defaultdict
I'm familiar with the use of the iteritems() and items() use with the standard dictionary which can be coupled with a for loop to scan over keys and values. 我熟悉标准字典的iteritems()和items()用法,可以将其与for循环结合使用以扫描键和值。 However how can I best do this with the default dict.
但是,我怎样才能最好地使用默认字典。 For example, I'd like to check that a given value does not show up in either the key or any of the values associated with any key.
例如,我想检查给定的值在键或与任何键关联的任何值中均未显示。 I'm currently trying the following:
我目前正在尝试以下方法:
for key, val in dic.iteritems():
print key, val
however I get the following: 但是我得到以下内容:
1 deque([2, 2])
and I have the following declarations for the variables/dictionary 我对变量/字典有以下声明
from collections import defaultdict, deque
clusterdict = defaultdict(deque)
So how do I best get at key values? 那么如何最好地获得关键价值呢? Thanks!
谢谢!
In general, for a defaultdict dd , to check whether a value x is used as a key do this: 通常,对于defaultdict dd ,要检查是否将值x用作键,请执行以下操作:
x in dd
To check whether x is used as a value do this: 要检查x是否用作值,请执行以下操作:
x in dd.itervalues()
In your case (a defaultdict with deques as values), you may want to see whether x is in any of the deques: 对于您的情况(使用双端队列作为值的defaultdict),您可能需要查看x是否在任何双端队列中:
any(x in deq for deq in dd.itervalues())
Remember, defaultdicts behave like regular dictionaries except that they create new entries automatically when doing d[k]
lookups on missing keys; 请记住,defaultdict的行为与常规词典类似,不同之处在于它们在对丢失的键进行
d[k]
查找时会自动创建新条目; otherwise, they behave no differently than regular dicts. 否则,它们的行为与常规命令没有什么不同。
If I understood your question: 如果我了解您的问题:
for key, val in dic.iteritems():
if key!=given_value and not given_value in val:
print "it's not there!"
Unless you meant something else... 除非你有别的意思...
I made this for Python 3: 我是为Python 3制作的:
from collections import defaultdict
count_data = defaultdict(int)
count_data[1] = 10
query = 2
if query in count_data.values():
print('yes')
Edit
编辑
You can use Counter dictionary too: 您也可以使用Counter字典:
from collections import Counter
count_data = Counter()
count_data[1] = 10
query = 2
if query in count_data.values():
print('yes')
stuff = 'value to check'
if not any((suff in key or stuff in value) for key, value in dic.iteritems()):
# do something if stuff not in any key or value
http://docs.python.org/library/collections.html#collections.defaultdict http://docs.python.org/library/collections.html#collections.defaultdict
So you can use iteritems 这样就可以使用迭代项目
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.