Ewdlam
Ewdlam

Reputation: 935

how to avoid for loop to append dictionary values in a list

I have this dictionary :

Dict = {
    "a" : 1,
    "b" : 2,
    "c" : 3
}

And these two lists :

List1 = ["a","c"]
List2 = [0]

Is there a more efficient way to append to List2 the corresponding values of List1 through Dict than the following way? :

for e in List1:
    List2.append(Dict[e]) 

Result :

[0, 1, 3]

Upvotes: 0

Views: 186

Answers (1)

chepner
chepner

Reputation: 531125

Probably not any more efficient in terms of running time, but more efficient in terms of code written:

List2.extend(Dict[e] for e in List1)

If you are interested in code golf,

List2.extend(map(Dict.get, List1))

Upvotes: 3

Related Questions