<p>可以通过创建一个字典来实现这一点,其中包含<code>result</code>dict中每个不同值的所有匹配键(其中值本身就是dict)。这是Python中相当常见的模式,遍历一个容器并将值聚合到dict中。然后,一旦创建了聚合dict,就可以将其拆分为重复值和单个值。你知道吗</p>
<p>要构建聚合dict,需要使用<code>result</code>中的每个子目录作为键,并将原始dict中匹配的键附加到与该子目录相关联的列表中。挑战在于不能将子目录直接用作字典键,因为它们是不可散列的。但是你可以通过把它们转换成元组来解决这个问题。元组也应该被排序,以避免丢失的重复项以不同的顺序出现。你知道吗</p>
<p>只需看一些示例代码,可能更容易理解:</p>
<pre><code>result = {
123: {'route1': 'abc', 'route2': 'abc1'},
456: {'route1': 'abc', 'route2': 'abc1'},
789: {'route1': 'abc2', 'route2': 'abc3'},
101: {'route1': 'abc', 'route2': 'abc1'},
102: {'route1': 'ab4', 'route2': 'abc5'}
}
# make a dict showing all the keys that match each subdict
cross_refs = dict()
for key, subdict in result.items():
# make hashable version of subdict (can't use dict as lookup key)
subdict_tuple = tuple(sorted(subdict.items()))
# create an empty list of keys that match this val
# (if needed), or retrieve existing list
matching_keys = cross_refs.setdefault(subdict_tuple, [])
# add this item to the list
matching_keys.append(key)
# make lists of duplicates and non-duplicates
dups = {}
singles = {}
for subdict_tuple, keys in cross_refs.items():
# convert hashed value back to a dict
subdict = dict(subdict_tuple)
if len(keys) > 1:
# convert the list of matching keys to a tuple and use as the key
dups[tuple(keys)] = subdict
else:
# there's only one matching key, so use that as the key
singles[keys[0]] = subdict
print(dups)
# {
# (456, 123, 101): {'route2': 'abc1', 'route1': 'abc'}
# }
print(singles)
# {
# 789: {'route2': 'abc3', 'route1': 'abc2'},
# 102: {'route2': 'abc5', 'route1': 'ab4'}
# }
</code></pre>