Austin Rock
Austin Rock

Reputation: 29

Comparing list values to the key values of a dictionary

I have a list of codes

l = [1, 2, 3, 4]

And a dictionary of previously seen codes and their translation

d = {1: 'A', 2: 'B', 3: 'C' }

I am trying to compare the list values to the dict key and create a new dict with the dict values of the matches. I accomplished this with the code below:

x = {k: d[k] for k in l if k in d}

However I also want to keep the list values that don't appear in the existing dict because these it is important to track new values. I would like to store these in the new dict with the val being 'no match' or something. I am not sure how to do this in a pythonic way.

Final dict:

{1: 'A', 2: 'B', 3: 'C', 4: 'no match'}

I know that this can be done by creating a dataframe from the dictionary and a dataframe from the list & outer joining but I would like to get better at dictionaries if possible!

Upvotes: 1

Views: 75

Answers (1)

Richard E
Richard E

Reputation: 3432

You can use dict.get(), which can take a default value that is returned in case the key is not found in the dictionary:

x = {k: d.get(k, 'no match') for k in l} 

Upvotes: 5

Related Questions