Python - comparing values in the same dictionary

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

I have a dictionary:

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


        
2条回答
  •  再見小時候
    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']}
    

提交回复
热议问题