Reputation: 573
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. 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!
Upvotes: 2
Views: 12729
Reputation: 9531
I made this for 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:
from collections import Counter
count_data = Counter()
count_data[1] = 10
query = 2
if query in count_data.values():
print('yes')
Upvotes: 1
Reputation: 597143
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
Upvotes: 0
Reputation: 226506
In general, for a defaultdict dd, to check whether a value x is used as a key do this:
x in dd
To check whether x is used as a value do this:
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:
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; otherwise, they behave no differently than regular dicts.
Upvotes: 3
Reputation: 266
http://docs.python.org/library/collections.html#collections.defaultdict
So you can use iteritems
Upvotes: -2
Reputation: 3572
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...
Upvotes: 2