How to select a certain key value and skip if a certain key is not present in the list of dictionaries?
Question:
d = [{'email': '[email protected]', 'gid': '5b869a4fe1cd8e14a38d67b5', '_id': '53f49508dabfaeb4c677b4a4', 'name': 'Hiromasa Habuchi', 'org': 'Department of Mathematics and Statistics, University of Victoria, Victoria, BC, V8W 3R4, Canada', 'orgid': '5f71b2841c455f439fe3c6c9'}, {'_id': '53f43522dabfaee4dc7780b2'}, {'_id': '560175f745cedb3395e5a530'}]
d is the list of dictionaries. I want to select the key[‘name’] value. Since other dictionaries in the list don’t have a key[‘name’] so I want to skip them.
Answers:
You can use a list comprehension that will check for each dictionary if the key name
belongs to the dictionary list of keys.
dicts = [{'email': '[email protected]', 'gid': '5b869a4fe1cd8e14a38d67b5', '_id': '53f49508dabfaeb4c677b4a4', 'name': 'Hiromasa Habuchi', 'org': 'Department of Mathematics and Statistics, University of Victoria, Victoria, BC, V8W 3R4, Canada', 'orgid': '5f71b2841c455f439fe3c6c9'},
{'_id': '53f43522dabfaee4dc7780b2'},
{'_id': '560175f745cedb3395e5a530'}]
[d for d in dicts if 'name' in d.keys()]
Output:
[{'_id': '53f49508dabfaeb4c677b4a4',
'email': '[email protected]',
'gid': '5b869a4fe1cd8e14a38d67b5',
'name': 'Hiromasa Habuchi',
'org': 'Department of Mathematics and Statistics, University of Victoria, Victoria, BC, V8W 3R4, Canada',
'orgid': '5f71b2841c455f439fe3c6c9'}]
d = [{'email': '[email protected]', 'gid': '5b869a4fe1cd8e14a38d67b5', '_id': '53f49508dabfaeb4c677b4a4', 'name': 'Hiromasa Habuchi', 'org': 'Department of Mathematics and Statistics, University of Victoria, Victoria, BC, V8W 3R4, Canada', 'orgid': '5f71b2841c455f439fe3c6c9'}, {'_id': '53f43522dabfaee4dc7780b2'}, {'_id': '560175f745cedb3395e5a530'}]
d is the list of dictionaries. I want to select the key[‘name’] value. Since other dictionaries in the list don’t have a key[‘name’] so I want to skip them.
You can use a list comprehension that will check for each dictionary if the key name
belongs to the dictionary list of keys.
dicts = [{'email': '[email protected]', 'gid': '5b869a4fe1cd8e14a38d67b5', '_id': '53f49508dabfaeb4c677b4a4', 'name': 'Hiromasa Habuchi', 'org': 'Department of Mathematics and Statistics, University of Victoria, Victoria, BC, V8W 3R4, Canada', 'orgid': '5f71b2841c455f439fe3c6c9'},
{'_id': '53f43522dabfaee4dc7780b2'},
{'_id': '560175f745cedb3395e5a530'}]
[d for d in dicts if 'name' in d.keys()]
Output:
[{'_id': '53f49508dabfaeb4c677b4a4',
'email': '[email protected]',
'gid': '5b869a4fe1cd8e14a38d67b5',
'name': 'Hiromasa Habuchi',
'org': 'Department of Mathematics and Statistics, University of Victoria, Victoria, BC, V8W 3R4, Canada',
'orgid': '5f71b2841c455f439fe3c6c9'}]