python get dictionary values list as list if key match - python

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])

Related

How to Mix 2 list as Dictionary in Python with custom key value pair

I have 2 List
1. Contains Keys
2. Contains Keys+Values
Now I have to make a Dictionary from it which will filter out the keys and insert all the values before the next key arrives in the list.
Example:
List 1: ['a','ef','ddw','b','rf','re','rt','c','dc']
List 2: ['a','b','c']
Dictionary that I want to create: {
'a':['ef','ddw'],
'b':['rf','re','rt'],
'c':['dc']
}
I am only familiar with python language and want solution for same in python only.
I think this should work:
result = {}
cur_key = None
for key in list_1:
if key in list_2:
result[key] = []
cur_key = key
else:
result[cur_key].append(key)

Find dictionary key using value from list

i'm trying to find a element in a list and return the the key who has that list.
Example:
mydict = {'hi':[1,2], 'hello':[3,4]}
print(find(1))
return 'hi
Is there any simple way to do it?
This function will return all the keys that contain the given value as a list.
def find(to_find, inp_dct):
return [i for i in inp_dct if to_find in inp_dct[i]]
You can simply loop through your dictionary as key,value pairs and your search value is in values list, it will return the value.
Code:
mydict = {'hi':[1,2], 'hello':[3,4]}
def find(item):
for key, value in mydict.items():
if item in value:
return key
print(find(1))
Output: hi
for k in mydict:
if val in mydict[k]:
print(k)
Where val is the value you want to find.

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/

List comprehensions - extracting values from a dictionary in a dictionary

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.

Remove all elements from the dictionary whose key is an element of a list

How do you remove all elements from the dictionary whose key is a element of a list?
for key in list_:
if key in dict_:
del dict_[key]
[Note: This is not direct answer but given earlier speculation that the question looks like homework. I wanted to provide help that will help solving the problem while learning from it]
Decompose your problem which is:
How to get a element from a list
How to delete a key:value in dictionary
Further help:
How do get all element of a list on python?
For loop works on all sequences and list is a sequence.
for key in sequence: print key
How do you delete a element in dictionary?
use the del(key) method.
http://docs.python.org/release/2.5.2/lib/typesmapping.html
You should be able to combine the two tasks.
map(dictionary.__delitem__, lst)
d = {'one':1, 'two':2, 'three':3, 'four':4}
l = ['zero', 'two', 'four', 'five']
for k in frozenset(l) & frozenset(d):
del d[k]
newdict = dict(
(key, value)
for key, value in olddict.iteritems()
if key not in set(list_of_keys)
)
Later (like in late 2012):
keys = set(list_of_keys)
newdict = dict(
(key, value)
for key, value in olddict.iteritems()
if key not in keys
)
Or if you use a 2.7+ python dictionary comprehension:
keys = set(list_of_keys)
newdict = {
key: value
for key, value in olddict.iteritems()
if key not in keys
}
Or maybe even a python 2.7 dictionary comprehension plus a set intersection on the keys:
required_keys = set(olddict.keys()) - set(list_of_keys)
return {key: olddict[key] for key in required_keys}
Oh yeah, the problem might well have been that I had the condition reversed for calculating the keys required.
for i in lst:
if i in d.keys():
del(d[i])
I know nothing about Python, but I guess you can traverse a list and remove entries by key from the dictionary?

Categories