I am creating a list of dictionaries from a separate list of dictionaries and transforming the content. I would like to conditionally exclude keys during the comprehension, but I'm not sure how. Here's an example of what I'm trying to do:
old_dict_list = [
{ 'old_key_1': 'value1a', 'old_key_2': 'value2a', 'old_key_3': 'value3a'},
{ 'old_key_1': 'value1b', 'old_key_2': 'value2b', 'old_key_3': 'value3b'},
]
new_dict_list = [
{
'new_key1': old_dict['old_key_1'],
'new_key2': old_dict['old_key_2'], # exclude this key entirely if some condition is met
'new_key3': old_dict['old_key_3'],
}
for old_dict in old_dict_list
]
print(new_dict_list)
I don't know of any way to conditionally exclude a key entirely when using comprehension like this. The only idea I've had is to use a fixed key value like None when the condition is met, then make a separate pass through the list of dictionaries and remove those None keys.
Is there any way to do this in just the one comprehension pass?
I wouldn't get hung up on the fact you are making your new list in a comprehension.
Clearly if you can transform a dictionary from the old format to the new format this is just
new = [transform(o) for o in old]
Your question then is "can I write a function to transform", which is "yes" if there is any way to describe what you are trying to do (your example is far from complete):
def transform(old):
return {new(k): v for k, v in old.items() if condition(k, v)}
def new(key):
return {'old_key_1': 'new_key1', ...}[key]
def condition(key, value):
if key == 'old_key_2' and value == 'value2b':
return False
return True