Created
April 21, 2021 21:01
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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