Python - comparing values in the same dictionary

前端 未结 2 1103
别跟我提以往
别跟我提以往 2021-01-07 17:17

I have a dictionary:

d = {\'Trump\': [\'MAGA\', \'FollowTheMoney\'],
     \'Clinton\': [\'dems\', \'Clinton\'],
     \'Stein\': [\'FollowTheMoney\', \'Atlant         


        
2条回答
  •  我在风中等你
    2021-01-07 18:05

    You can use Counter to tally how many times each value appears in d.

    d = {'Trump': ['MAGA', 'FollowTheMoney'],
         'Clinton': ['dems', 'Clinton'],
         'Stein': ['FollowTheMoney', 'Atlanta']}
    
    from collections import Counter
    
    c = Counter(x for xs in d.values() for x in xs)
    

    In this example, the value of c is

    Counter({'Atlanta': 1,
             'Clinton': 1,
             'FollowTheMoney': 2,
             'MAGA': 1,
             'dems': 1})
    

    Then choose values for which the count is exactly 1.

    update_d = {k: [v for v in vs if c[v] == 1] for k, vs in d.items()}
    

提交回复
热议问题