EDITED input and output based on comments to make the question more clear.
I have a dictionary with unique keys, but some of them represent different tiers of the same dataset (they have the same name except for the last two characters).
EDIT: Not every dataset is generated with every tier, so there might be datasets which are only available at tier "T1", while others are available for multiple tiers. (END OF EDIT)
I also have a tuple holding the tier levels. Now I want to filter the dictionary to contain only the "best" available tier. The tier is part of the key, but can also be taken from the value of each dictionary entry. Here is a MWE:
my_dict = {
'LC08_L1TP_200029_20210716_20210721_02_T1': { # best tier for this dataset --> keep it
'cc': 30.57,
'tier': 'T1',
},
'LC08_L1TP_200029_20210716_20210721_02_RT': { # worst tier for this dataset --> remove it
'cc': 30.57,
'tier': 'RT',
},
'LC08_L1TP_200029_20210630_20210708_02_T2': { # worst tier for this dataset --> remove it
'cc': 60.52,
'tier': 'T2',
},
'LC08_L1TP_200029_20210630_20210708_02_RT': { # best tier for this dataset --> keep it
'cc': 60.52,
'tier': 'RT',
},
'LC08_L1TP_200029_20210614_20210628_02_T2': { # only tier for this datset --> keep it
'cc': 15.61,
'tier': 'T2',
},
}
tiers = ('T1', 'RT', 'T2') # this is the tier order
In the end, I want a new dictionary that looks like this, holding only the "best" available tier based on tiers
:
{
'LC08_L1TP_200029_20210716_20210721_02_T1': {
'cc': 30.57,
'tier': 'T1',
},
'LC08_L1TP_200029_20210630_20210708_02_RT': {
'cc': 60.52,
'tier': 'RT',
},
'LC08_L1TP_200029_20210614_20210628_02_T2': {
'cc': 15.61,
'tier': 'T2',
},
}
I know the key=lambda x
functionality for sorting, as described at How do I sort a list of dictionaries by a value of the dictionary?, but just sorting is not what I'm aiming at.
Also thought of something like this, but it obviously does not work as I need it:
for key in my_dict.keys():
for tier in tiers:
if key.endswith(tier):
new_dict[key] = my_dict[key]
break