Key with multiple values - check if value is in dictionary python - python

I have a dictionary that has a list of multiple values stored for each key. I want to check if a given value is in the dictionary, but this doesn't work:
if 'the' in d.values():
print "value in dictionary"
Why doesn't it work with multiple values stored as a list? Is there any other way to test if the value is in the dictionary?

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"

It should be pretty simple:
>>> d = { 'a': ['spam', 'eggs'], 'b': ['foo', 'bar'] }
>>> 'eggs' in d.get('a')
True

You can iterate over the dictionary.
If your dictionary looks like follows:
my_dictionary = { 'names': ['john', 'doe', 'jane'], 'salaries': [100, 200, 300] }
Then you could do the following:
for key in my_dictionary:
for value in my_dictionary[key]:
print value
You can naturally search instead of print. Like this:
for key in my_dictionary:
for value in my_dictionary[key]:
if "keyword" in value:
print "found it!"
There is probably a shorter way to do this, but this should work too.

If you just want to check whether a value is there or not without any need to know the key it belongs to and all, you can go with this:
if 'the' in str(d.values())
Or for a one-liner, you can use the filter function
if filter(lambda x: 'eggs' in x, d.values()) # To just check
filter(lambda x: 'eggs' in d[x] and x, d) # To get all the keys with the value

I like to write
if 0 < len([1 for k in d if 'the' in d[k]]):
# do stuff
or equivalently
if 0 < len([1 for _,v in d.iteritems() if 'the' in v]):
# do stuff

Related

Python add key to list of dictionary if key doesn't exist

I want to add the key 'Name' to list of dictionaries in whichever dictionary 'Name' doesn't exist.
For example,
[dict(item, **{'Name': 'apple'}) for item in d_list]
will update value of key 'Name' even if key already exists and
[dict(item, **{'Name': 'apple'}) for item in d_list if 'Name' not in item]
returns empty list
You need to handle the two different cases. In case the list is empty, and if it's not.
It's not possible to handle both use-cases in a single list comprehension statement since when the list is empty, it will always return zero-value (empty list). It is like doing for i in my_list. If the list is empty, the code inside the for block won't be executed.
I would tackle it with a single loop. I find it more readable.
>>> default = {"Name": "apple"}
>>> miss_map = {"Data": "text"}
>>> exist_map = {"Name": "pie"}
>>>
>>> d = [miss_map, exist_map]
>>>
>>> list_dict = [miss_map, exist_map]
>>> for d in list_dict:
... if "Name" not in d.keys():
... d.update(default)
...
>>> list_dict
[{'Data': 'text', 'Name': 'apple'}, {'Name': 'pie'}]
>>>
You can then move it to it's own function and pass it the list of dicts.
In one line of code:
d_list = [{**d, "Name": "apple"} for d in d_list if "Name" not in d] + [d for d in d_list if "Name" in d]
Based on Abdul Aziz comment, I could do it in 1 line using
[item.setdefault("Name", 'apple') for item in d_list]

How to access key by value in a dictionary?

I have a dict that looks like the following:
d = {"employee": ['PER', 'ORG']}
I have a list of tags ('PER', 'ORG',....) that is extracted from the specific entity list.
for t in entities_with_tag: # it includes words with a tag such as: [PER(['Bill']), ORG(['Microsoft']),
f = t.tag # this extract only tag like: {'PER, ORG'}
s =str(f)
q.add(s)
Now I want if {'PER, ORG'} in q, and it matched with d.values(), it should give me the keys of {'PER, ORG'} which is 'employee'. I try it this but does not work.
for x in q:
if str(x) in str(d.values()):
print(d.keys()) # this print all the keys of dict.
If I understand correctly you should loop he dictionary instead of the tag list. You can check if the dictionary tags are in the list using sets.
d = {"employee": ['PER', 'ORG'],
"located": ["ORG", "LOC"]}
q = ["PER", "ORG", "DOG", "CAT"]
qset = set(q)
for key, value in d.items():
if set(value).issubset(qset):
print (key)
Output:
employee
You mean with... nothing?
for x in q:
if str(x) in d.values():
print(d.keys())
What you can do is to switch keys and values in the dict and then access by key.
tags = ('PER', 'ORG')
data = dict((val, key) for key, val in d.items())
print(data[tags])
Just be careful to convert the lists in tuples, since lists are not hashable.
Another solution would be to extract both key and value in a loop. But that's absolutely NOT efficient at all.
for x in q:
if str(x) in str(d.values()):
for key, val in d.items():
if val == x:
print(key) # this print all the keys of dict.
What you can do is make two lists. One which contains the keys and one which contains the values. Then for the index of the required value in the list with values you can call the key from the list of keys.
d = {"employee": ['PER', 'ORG']}
key_list = list(d.keys())
val_list = list(d.values())
print(key_list[val_list.index(['PER','ORG'])
Refer: https://www.geeksforgeeks.org/python-get-key-from-value-in-dictionary/

Dictionary get value without knowing the key

In python if I have a dictionary which has a single key value pair and if I don't know what the key might be, how can I get the value?
(and if I have a dict with more than 1 key, value pair, how can I return any one of the values without knowing any of the keys?)
You just have to use dict.values().
This will return a list containing all the values of your dictionary, without having to specify any key.
You may also be interested in:
.keys(): return a list containing the keys
.items(): return a list of tuples (key, value)
Note that in Python 3, returned value is not actually proper list but view object.
Other solution, using popitem and unpacking:
d = {"unknow_key": "value"}
_, v = d.popitem()
assert v == "value"
Further to Delgan's excellent answer, here is an example for Python 3 that demonstrates how to use the view object:
In Python 3 you can print the values, without knowing/using the keys, thus:
for item in my_dict:
print( list( item.values() )[0] )
Example:
cars = {'Toyota':['Camry','Turcel','Tundra','Tacoma'],'Ford':['Mustang','Capri','OrRepairDaily'],'Chev':['Malibu','Corvette']}
vals = list( cars.values() )
keyz = list( cars.keys() )
cnt = 0
for val in vals:
print('[_' + keyz[cnt] + '_]')
if len(val)>1:
for part in val:
print(part)
else:
print( val[0] )
cnt += 1
OUTPUT:
[_Toyota_]
Camry
Turcel
Tundra
Tacoma
[_Ford_]
Mustang
Capri
OrRepairDaily
[_Chev_]
Malibu
Corvette
That Py3 docs reference again:
https://docs.python.org/3.5/library/stdtypes.html#dict-views
Two more ways:
>>> d = {'k': 'v'}
>>> next(iter(d.values()))
'v'
>>> v, = d.values()
>>> v
'v'
One more way: looping with for/in through a dictionary we get the key(s) of the key-value pair(s), and with that, we get the value of the value.
>>>my_dict = {'a' : 25}
>>>for key in my_dict:
print(my_dict[key])
25
>>> my_other_dict = {'b': 33, 'c': 44}
>>> for key in my_other_dict:
print(my_other_dict[key])
33
44

Python a list and a dictionary

I have a list (x) and a dictionary (d)
x=[1,3,5]
d={1:a,2:b,3:c,4:d,5:e}
As you can see a few variables match a few keys in the dictionary
But how can I print only the values whose key matches a variable in the list?
I tried a for loop but it returns only the key. Thanks for any assistance!
Something like this?
for key in d:
if key in x:
print d[key]
This will loop through every key in the dictionary, and if the key appears in x then it will print the value of x.
try like this:
>>> x=[1,3,5]
>>> d={1:'a',2:'b',3:'c',4:'d',5:'e'}
>>> for key in d.keys():
... if key in x:
... print d[key]
...
a
c
e
or you can use dict.get:
>>> for num in x:
... print d.get(num,"not found")
...
a
c
e
dict.get will give the value of key, if key is found in dictionary else defaultvalue
syntax : dict.get(key[, default])
If you are sure that all of the keys in x are in your dictionary
for key in x:
print(d[key])
Otherwise you can check first
for key in x:
if x in d:
print(d[key])
You can use this one-liner list comprehension:
[d[key] for key in x if key in d]
This will also work if not all items in the list are keys in the dictionary.
for example:
>>> d = {1:'a', 3:'b'}
>>> x = [1, 2]
>>> [d[key] for key in x if key in d]
... ['a']

Getting Keys Using Unique Values in Dictionary

I have a code like this.When i'm executing this it prints only 'hello' but i want both. I want to print both keys in my dictionary because i'm passing here unique value can any one help me.
mydict = {'hai': 35, 'hello': 35}
print mydict.keys()[mydict.values().index(35)]
index() only returns the first match by design. The best solution is probably a list comprehension:
>>> keys = [key for key,value in mydict.iteritems() if value==35]
>>> keys
['hello', 'hai']
mydict = {'hai':35,'hello':35}
a=[]
for k, v in mydict.iteritems():
if v == 35:
a.append(k)
print a

Categories