<p>据我所知,“最佳”是指具有最大<code>cc</code>值的<em>层</em></p>
<ul>
<li>您需要首先根据<code>cc</code>键对字典进行排序(<em>)以简化筛选</李>
<li>迭代<code>tiers</code>元组和排序字典,并将匹配的<code>tiers</code>项存储到字典-<code>new_dict</code></li>
<li>我使用了<code>visited</code>{<cd7>}来避免再次访问<code>tiers</code></李>
</ul>
<p><strong>编辑</strong></p>
<blockquote>
<p>You don't need to use a <code>set</code>. Just a <code>break</code> would do. <em>Based on @Xitiz comment.</em></p>
</blockquote>
<p>代码如下:</p>
<pre><code>my_dict = {
'LC08_L1TP_200029_20210716_20210721_02_T1': {
'cc': 30.57,
'tier': 'T1',
},
'LC08_L1TP_200029_20210716_20210721_02_RT': {
'cc': 30.57,
'tier': 'RT',
},
'LC08_L1TP_200029_20210630_20210708_02_T2': {
'cc': 60.52,
'tier': 'T2',
},
'LC08_L1TP_200029_20210630_20210708_02_RT': {
'cc': 60.52,
'tier': 'RT',
}
}
tiers = ('T1', 'RT', 'T2') # this is the tier order
# Sorting the dict based on 'cc' in descending order
my_dict = dict(sorted(my_dict.items(), key=lambda x: -x[1]['cc']))
new_dict = {}
for i in tiers:
for k,v in my_dict.items():
if v['tier'] == i:
new_dict.update({k: v})
break
print(new_dict)
</code></pre>
<p>输出:</p>
<pre><code>{
{
'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_20210630_20210708_02_T2': {
'cc': 60.52,
'tier': 'T2'
}
}
</code></pre>