Yatin Hasija
Yatin Hasija

Reputation: 33

How can I iterate a dictionary over a list and get values as result in list

I can't put exact query but this is the reference I want to iterate over a list and find the values of element and store result in list.

# dict and list are already given to us, we need to iterate over list and check for the elements as key and append the values in a list.

dict = {"a":"apple", "b":"ball"}

list = ["a", "a", "b"]

#output need to be like:
["apple","apple","ball"]

Upvotes: 0

Views: 61

Answers (3)

MichaelT572
MichaelT572

Reputation: 328

Use a for loop to iterate over the list, then just append the dictionary value for each element to some other list

d = {"a":"apple","b":"ball"}

l = ["a","a","b"]

output = []

for i in l:
    output.append(d[i])

print(output)

Upvotes: 1

Anvesh
Anvesh

Reputation: 625

Check out list comprehensions in python https://www.w3schools.com/python/python_lists_comprehension.asp

[dict[i] for i in list]

Upvotes: 0

maziyank
maziyank

Reputation: 616

The very quick way just to make an iteration, and access the dictionary key for each iteration

result = []
for x in list:
    result.append(dict[x])
print(result)

or

result = [dict[x] for x in list]

Upvotes: 0

Related Questions