0

在字典中有重复的值,例如:

dict_numbers={'one':['one', 'first','uno', 'une'],
            'zero':['zero','nothing','cero'],
            'first':['one', 'first','uno', 'une'],
            'dos':['two','second','dos', 'segundo','deux'],
            'three':['three','tres','third','tercero'],
            'second':['two','second','dos','segundo','deux'],
            'forth':['four','forth', 'cuatro','cuarto'],
            'two': ['two','second','dos', 'segundo','deux'],
            'segundo':['two','second','dos', 'segundo','deux']}

我想获得具有重复值的键的第一次出现。请注意,字典没有重复的键,而是重复的值。在这个例子中,我会得到一个列表来保存重复值的第一次出现:

list_numbers_no_duplicates=['one','zero','dos','three','forth']

first键被删除,因为one已经具有相同的值。 second键被删除,因为dos已经具有相同的值。 two键被删除,因为dos已经具有相同的值。

如何跟踪键值中的几个重复项?

提前致谢

4

1 回答 1

1

希望我正确理解了您的目标。以下用途chain来自非常有用的 itertools 包。

    >>> {key: vals for i, (key, vals) in enumerate(dict_numbers.items()) 
        if key not in chain(*list(dict_numbers.values())[:i])}
    {'one': ['one', 'first', 'uno', 'une'], 
    'zero': ['zero', 'nothing', 'cero'], 
    'dos': ['two', 'second', 'dos', 'segundo', 'deux'], 
    'three': ['three', 'tres', 'third', 'tercero'], 
    'forth': ['four', 'forth', 'cuatro', 'cuarto']}

本质上,这是通过为在前面的任何列表中没有找到键的条目重新创建原始字典来工作的(因此是枚举和切片恶作剧)。

于 2020-10-06T02:21:27.867 回答