Python - comparing values in the same dictionary

前端 未结 2 1077
别跟我提以往
别跟我提以往 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()}
    
    0 讨论(0)
  • 2021-01-07 18:08

    Not as elegant as using Counter, but does remove duplicates without the use of modules:

    d = {'Trump': ['MAGA', 'FollowTheMoney'],
        'Clinton': ['dems', 'Clinton'],
        'Stein': ['FollowTheMoney', 'Atlanta']}
    
    dupvals = [item for sublist in d.values() for item in sublist] # get all values from all keys into a list
    dups = [] # list to hold duplicates
    
    for i in dupvals:
        if dupvals.count(i) > 1:
            dups.append(i)
    
    dupvals = set(dups) # keep only one item for each duplicated item
    
    new_d = {}
    
    for key,values in d.items():
        for value in values:
            if not value in dupvals:
                new_d.setdefault(key, []).append(value)
    
    print new_d # {'Clinton': ['dems', 'Clinton'], 'Trump': ['MAGA'], 'Stein': ['Atlanta']}
    
    0 讨论(0)
提交回复
热议问题