有没有一种方法可以从字典中提取相似的(键,值)组合

时间:2019-07-04 07:20:20

标签: python list dictionary tree

输入字典,我需要根据规则将元素分开

ToSep = {'a': 'd', 'b': 'a', 'c': 'a', 'l': 'm', 'm': 'l', 'e': 'b', 'd': 'a'}

请注意,键“ l”和“ m”具有可互换的值,我需要从字典中提取这些值并将其移至列表。

这就是我要寻找的两个列表:

['a','b','c','e','d'] &
['l','m']

1 个答案:

答案 0 :(得分:0)

您可以通过以下列表理解来分隔满足条件的键:

interchangeable = [key for key in ToSep.keys() if ToSep[key] in ToSep.keys() and key == ToSep[ToSep[key]]]

not_interchangeable = [key for key in ToSep.keys() if ToSep[key] not in ToSep.keys() or key != ToSep[ToSep[key]]]