0

我有一个包含键值对的字典,其中的值也是字典:

{ 
    'item1':{'name':'filename', 'size':1024},
    'item2':{'name':'filename', 'size':1024},
    'item3':{'name':'diff_filename', 'size':1024},
    'item4':{'name':'diff_filename', 'size':1024}
}

我想删除字典中在其值中具有重复的“文件名”字段的项目,从而得到结果:

{ 
    'item1':{'name':'filename', 'size':1024},
    'item3':{'name':'diff_filename', 'size':1024}
}
4

1 回答 1

4

使用辅助工具set来跟踪您已经看到的文件名:

seen = set()
{k: v for k, v in yourdict.iteritems() 
    if v['name'] not in seen and (seen.add(v['name']) or True)}

或者,作为循环更具可读性:

seen = set()
filtered = dict()
for k, v in yourdict.iteritems():
    if v['name'] in seen:
        continue
    seen.add(v['name'])
    filtered[k] = v
于 2012-08-13T10:28:56.343 回答