If I understand you correctly, you're looking for something like that:
>>> d = {'galaxy': 5, 'apple': 6, 'nokia': 5}
>>> { k:v for k,v in d.items() if v==5 }
{'nokia': 5, 'galaxy': 5}
Answer from Ohad Eytan on Stack OverflowFor example, given the dictionary:
dict = {
character1: ['assassin', 'mage'] , character2:['assassin', 'fighter'] , character3:['assassin' ]
}
what would be the best way to append all the keys that contain the value 'assassin' , but do not contain other values, such as "mage" and "fighter"?
I figured i could just do this:
assassins = []
for x in dict:
if "assassins" in dict[x] and "mage" not in dict[x] and "fighter" not in
dict[x]:
assassins.append(x)but i feel like there's a better way.
Key with multiple values - check if value is in dictionary python - Stack Overflow
python - Dictionaries - Check key for multiple values - Stack Overflow
How to check if multiple values exists in a dictionary python - Stack Overflow
How to search for multiple values in a dictionary in python? - Stack Overflow
Well, you could do this:
>>> if all(k in foo for k in ("foo","bar")):
... print "They're there!"
...
They're there!
if {"foo", "bar"} <= myDict.keys(): ...
If you're still on Python 2, you can do
if {"foo", "bar"} <= myDict.viewkeys(): ...
If you're still on a really old Python <= 2.6, you can call set on the dict, but it'll iterate over the whole dict to build the set, and that's slow:
if set(("foo", "bar")) <= set(myDict): ...
d.values() usually stores the values in list format. So you need to iterate through the list contents and check for the substring the is present or not.
>>> d = {'f':['the', 'foo']}
>>> for i in d.values():
if 'the' in i:
print("value in dictionary")
break
value in dictionary
Your values is a list!
for item in d.values():
if 'the' in item:
print "value in dictionary"
Using the len builtin in python, you can check the length of a list. If the length of the value is more then 1 then there are more then one value in the list.
for key in dictionary: # loop through all the keys
value = dictionary[key] # get value for the key
if len(value) > 1:
break # stop loop if list length is more than 1
Note that this assumes that every value in the dictionary is a list or container.
It is not possible for a dictionary key to have more than one value: either the key is not present in the dictionary, so it has no value, or it is present, and it has one value.
That value may be a tuple, list, dictionary, etc., which contains multiple values, but it is still one value itself. The value may also be None which can be a marker for no value, but it is still a value.
As @Ulisha's comment said, if you try to assign a new value to a key, the new value will just replace the old value. Again, there can be at most one value for a given key, although there are ways to simulate multiple values by using container objects such a tuple, list, or dict.
If you are looking at a specific item and you want to test if it is a list, you can use
if isinstance(item, list):
This will also catch items that have a type that descends from list, such as a priority queue. If you want to expand that to also detect tuples, dicts, sets, and most other "containers", you can use
if isinstance(item, collections.Container):
For this you will, of course, need to import the collections module.
Remember that even if the item is a list, it may have no, one, or multiple items.
This should do what you want:
def check_value_exist(test_dict, value1, value2):
return all( v in test_dict for v in [value1,value2] )
Make values a set and you can use set.issubset to verify all values are in the dict:
def check_value_exist(word_freq, *values):
return set(values).issubset(word_freq)
print(check_value_exists(word_freq, 'at', 'test'))
print(check_value_exists(word_freq, 'at', 'test', 'bar'))
True
False
You can use set intersections:
if not d.viewkeys() & {'amount', 'name'}:
raise ValueError
In Python 3, that'd be:
if not d.keys() & {'amount', 'name'}:
raise ValueError
because .keys() returns a dict view by default. Dictionary view objects such as returned by .viewkeys() (and .keys() in Python 3) act as sets and intersection testing is very efficient.
Demo in Python 2.7:
>>> d = {
... 'name': 'name',
... 'date': 'date',
... 'amount': 'amount',
... }
>>> not d.viewkeys() & {'amount', 'name'}
False
>>> del d['name']
>>> not d.viewkeys() & {'amount', 'name'}
False
>>> del d['amount']
>>> not d.viewkeys() & {'amount', 'name'}
True
Note that this tests True only if both keys are missing. If you need your test to pass if either is missing, use:
if not d.viewkeys() >= {'amount', 'name'}:
raise ValueError
which is False only if both keys are present:
>>> d = {
... 'name': 'name',
... 'date': 'date',
... 'amount': 'amount',
... }
>>> not d.viewkeys() >= {'amount', 'name'}
False
>>> del d['amount']
>>> not d.viewkeys() >= {'amount', 'name'})
True
For a strict comparison (allowing only the two keys, no more, no less), in Python 2, compare the dictionary view against a set:
if d.viewkeys() != {'amount', 'name'}:
raise ValueError
(So in Python 3 that would be if d.keys() != {'amount', 'name'}).
if all(k not in d for k in ('name', 'amount')):
raise ValueError
or
if all(k in d for k in ('name', 'amount')):
# do stuff
Hello Reddit,
For a single key to match it very easy to check of the key is available:
if "keyname" in mydict:
#do something with if this key matches
To check if multiple keys are in the dict:
if {"keyname1", "keyname2"}.issubset(mydict):
#do something if both are in the dict
What I want is to check if one or two are in the dict:
if "keyname1" or "keyname2" in dict:
#this will not work as it will check:
# ("keyname1") or ("keyname2" in dict) and not
# ("keyname1" or "keyname2") in dict
#do something if one or more of them matchesHow do I achieve this?