Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jimbrayrcp/b6404c9a02a828470831773568c68c29 to your computer and use it in GitHub Desktop.
Save jimbrayrcp/b6404c9a02a828470831773568c68c29 to your computer and use it in GitHub Desktop.
Find a matching value in a dictionary from values found in a list you can choose to match on the key or the value with the conditional test :: Python3.9
# COMBINING DICTIONARY AND LIST COMPREHENSION
# python 3.9,
# Find a matching value in a dictionary from values found in a list.
# you can choose to match on the key or the value with the conditional test
# depending the type of dictionary
a_list = [1, 2, 3]
b_dict = {1: "Bill", 2: "Joe", 3: "Oscar", 4: "Paul", 5: "Sally"}
new_dict = dict((key, value) for key, value in b_dict.items() if key in a_list)
print(new_dict)
# RESULT: {1: 'Bill', 2: 'Joe', 3: 'Oscar'}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment