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/
Related
I have the following list and dictionary:
match_keys = ['61df50b6-3b50-4f22-a175-404089b2ec4f']
locations = {
'2c50b449-416e-456a-bde6-c469698c5f7': ['422fe2d0-b10f-446d-ac3c-f75e5a3ff138'],
'61df50b6-3b50-4f22-a175-404089b2ec4f': [
'7112fa59-63b1-4057-8822-fe11168c328f', '6d06ee0a-7447-4726-822f-942b9e12c9ce'
]
}
If I want to search 'locations' for keys that match in the match_keys list and extract their values, to get something like this...
['7112fa59-63b1-4057-8822-fe11168c328f', '6d06ee0a-7447-4726-822f-942b9e12c9ce']
...what would be the best way?
You can iterate over match_keys and use dict.get to get the values under each key:
out = [v for key in match_keys if key in locations for v in locations[key]]
Output:
['7112fa59-63b1-4057-8822-fe11168c328f', '6d06ee0a-7447-4726-822f-942b9e12c9ce']
for key, value in locations.items():
if key == match_keys[0]:
print(value)
Iterate over keys and get value by [].
res = []
for key in matched_keys:
res.append(matched_keys[key])
or if you dont want list of lists you can use extend()
res = []
for key in matched_keys:
res.extend(matched_keys[key])
I have a dictionary such as:
{2:'r', 4:'y', 5:'u', 7:'y', 13:'r', 17:'y'}
and I want a list: for every duplicated value the first key with that value . so in this example I want
[2, 4]
We can use a new dictionary to reverse k and v:
d = {2:'r', 4:'y', 5:'u', 7:'y', 13:'r', 17:'y'}
new_dict = {}
for k,v in d.items():
new_dict[v] = new_dict.get(v, []) + [k]
Now we have a new dictionary whose keys are values of the original dictionary and values are lists containing keys from the original dictionary whose values are now the key of the new dictionary. Now we have to check if there are more than 1 element in values:
duplicates = []
for k,v in new_dict.items():
if len(v)>1:
duplicates.append(v[0])
I'm trying to get a list of names from a dictionary of dictionaries...
list = {'1':{'name':'fred'}, '2':{'name':'john'}}
# this code works a-ok
for key, value in list.items():
names = []
for key, value in list.items():
names.append(value['name'])
# and these consecutive comprehensions also work...
keys = [value for key, value in list.items()]
names = [each['name'] for each in keys]
but how can the last two be combined?
>>> d = {'1':{'name':'fred'}, '2':{'name':'john'}}
You can use the following modification to your list comprehension
>>> [value.get('name') for key, value in d.items()]
['john', 'fred']
Although in this case, you don't need the key for anything so you can just do
>>> [value.get('name') for value in d.values()]
['john', 'fred']
names = [value['name'] for value in list.values()]
names = [value['name'] for key, value in list.items()]
names = [value['name'] for key, value in list.items()]
Since value is defined in the for part of the comprehension, you can perform operations on value for the item part of the comprehension. As noted above, you can simplify this by using list.values() instead.
dict1 = open('dict1.txt','r')
dict2 = open('dict2.txt','r')
keys = []
values = []
for w in dict1:
keys.append(w.strip())
for key in keys:
key
for x in dict2:
values.append(x.strip())
for val in values:
val
dictionary = {key: val}
Text files contain 140 lines of single words. 'keys' is a list of words from the first file, 'values' is a list of words from the second file.
Whenever I print the dictionary, I get only the first pair. How to loop it inside dictionary so I get all 140 pairs?
I've tried doing this:
dictionary = {}
val = dictionary[key]
But I get 'KeyError' on the console. I know this is basic stuff but I've been struggling with it.
You can easily build the dictionary using zip:
for w in dict1:
keys.append(w.strip())
for x in dict2:
values.append(x.strip())
dictionary = dict(zip(keys, values))
Your KeyError is due to the assignment being the wrong way around:
val = dictionary[key]
tries to assign what is currently in dictionary for the key (which is nothing) to val. Instead, it should be:
dictionary[key] = val
Your looping code is incorrect too:
for w in dict1:
keys.append(w.strip())
for key in keys: # looping over all keys so far each time
key # doesn't do anything
And your first attempt:
dictionary = {key: val}
would create a new dictionary each time.
Use zip() to combine the keys and values from the two files. You can produce the whole dictionary in one go with just two lines of code:
with open('dict1.txt','r') as keys, open('dict2.txt','r') as values:
dictionary = {key.strip(): value.strip() for key, value in zip(keys, values)}
Your code loops over the two files and after each loop, key and value are bound still to the last value of each iteration.
For example lets say we have the following dictionary:
dictionary = {'A':4,
'B':6,
'C':-2,
'D':-8}
How can you print a certain key given its value?
print(dictionary.get('A')) #This will print 4
How can you do it backwards? i.e. instead of getting a value by referencing the key, getting a key by referencing the value.
I don't believe there is a way to do it. It's not how a dictionary is intended to be used...
Instead, you'll have to do something similar to this.
for key, value in dictionary.items():
if 4 == value:
print key
In Python 3:
# A simple dictionary
x = {'X':"yes", 'Y':"no", 'Z':"ok"}
# To print a specific key (for instance the 2nd key which is at position 1)
print([key for key in x.keys()][1])
Output:
Y
The dictionary is organized by: key -> value
If you try to go: value -> key
Then you have a few problems; duplicates, and also sometimes a dictionary holds large (or unhashable) objects which you would not want to have as a key.
However, if you still want to do this, you can do so easily by iterating over the dicts keys and values and matching them as follows:
def method(dict, value):
for k, v in dict.iteritems():
if v == value:
yield k
# this is an iterator, example:
>>> d = {'a':1, 'b':2}
>>> for r in method(d, 2):
print r
b
As noted in a comment, the whole thing can be written as a generator expression:
def method(dict, value):
return (k for k,v in dict.iteritems() if v == value)
Python versions note: in Python 3+ you can use dict.items() instead of dict.iteritems()
target_key = 4
for i in dictionary:
if dictionary[i]==target_key:
print(i)
Within a dictionary if you have to find the KEY for the highest VALUE please do the following :
Step 1: Extract all the VALUES into a list and find the Max of list
Step 2: Find the KEY for the particular VALUE from Step 1
The visual analyzer of this code is available in this link : LINK
dictionary = {'A':4,
'B':6,
'C':-2,
'D':-8}
lis=dictionary.values()
print(max(lis))
for key,val in dictionary.items() :
if val == max(lis) :
print("The highest KEY in the dictionary is ",key)
I think this is way easier if you use the position of that value within the dictionary.
dictionary = {'A':4,
'B':6,
'C':-2,
'D':-8}
# list out keys and values separately
key_list = list(dictionary.keys())
val_list = list(dictionary.values())
# print key with val 4
position = val_list.index(4)
print(key_list[position])
# print key with val 6
position = val_list.index(6)
print(key_list[position])
# one-liner
print(list(my_dict.keys())[list(my_dict.values()).index(6)])
Hey i was stuck on a thing with this for ages, all you have to do is swap the key with the value e.g.
Dictionary = {'Bob':14}
you would change it to
Dictionary ={1:'Bob'}
or vice versa to set the key as the value and the value as the key so you can get the thing you want