I have a list and dict in python say,
list A = [1, 3]
dict B = {'apple':1, 'orange':3, 'carrot': 4}
so now I want to use list comprehension in python and get the list of keys with 'values' in list A.
Asked
Active
Viewed 83 times
0

new born
- 31
- 1
- 6
-
You realize you are running the dictionary "in reverse" right? – AirSquid May 19 '20 at 16:35
3 Answers
1
First you would need to loop through the dictionary, then check if the value is in the other list.
This can be done with or without list-comprehension.
Using list-comprehension:
value = [x for x in B if B[x] in A]
Without list-comprehension:
value = []
for x in B:
if B[x] in A:
value.append(x)

SherylHohman
- 16,580
- 17
- 88
- 94

Clinton Graham
- 122
- 8
-
While this code may resolve the OP's issue, it is best to include an explanation as to how your code addresses the OP's issue. In this way, future visitors can learn from your post, and apply it to their own code. SO is not a coding service, but a resource for knowledge. Also, high quality, complete answers are more likely to be upvoted. These features, along with the requirement that all posts are self-contained, are some of the strengths of SO as a platform, that differentiates it from forums. You can edit to add additional info &/or to supplement your explanations with source documentation. – SherylHohman May 19 '20 at 21:54
-
1
0
TL;DR
a = set([1,3])
b = {'apple':1, 'orange':3, 'carrot': 4}
# Filter dict b with a as keys
c = {k:v for k,v in b.items() if k in a}

alvas
- 115,346
- 109
- 446
- 738
-
-
Also, convert list a to `set(a)` to bring down the time complexity of `in` operation – mad_ May 19 '20 at 16:42
0
This small list comprehension should do.
a = [1,3]
b = {'apple':1, 'orange':3, 'carrot': 4}
print([x for x in b if b[x] in a])

apurvmishra99
- 388
- 1
- 3