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.
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 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/
If I had a dictionary where the value was set to a list by default, how could I go about searching all of these lists in the dictionary for a certain term?
For Example:
textbooks = {"math":("red", "large"), "history":("brown", "old", "small")}
With more terms and cases where the same thing might occur again, how could I say find all of the keys in which their value is a list containing "red"? In my example above, the only one I'd want it to find would be "math".
[k for k, v in textbooks.iteritems() if 'red' in v]
It is Pythonic shorthand for
res = []
for key, val in textbooks.iteritems():
if 'red' in val:
res.append(key)
See list comprehension in Python documentation
[key for key, corresponding_list in textbook.items() if 'red' in corresponding_list]
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
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?