python subset dictionary

Solutions on MaxInterview for python subset dictionary by the best coders in the world

showing results for - "python subset dictionary"
Ruairi
29 Feb 2020
1# Basic syntax:
2{key: value for key, value in a_dictionary.items() if condition}
3
4# Example usage:
5# Create dictionary:
6your_dictionary = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
7
8# Select keys whose value is greater than 2:
9{key: value for key, value in a_dictionary.items() if value > 2}
10--> {'c': 3, 'd': 4}
11
12keys_to_get = ['a', 'c']
13{key: value for key, value in a_dictionary.items() if key in keys_to_get}
14--> {'a': 1, 'c': 3}