python - Remove duplicate value from dictionary without removing key -
i'm new python , having learn trial , error, haven't been able find solution problem i'm having.
i have dictionary looks this:
mydict = {'key1': ['item1', 'item2', 'item3'], 'key2': ['item4', 'item5', 'item6'], 'key3': 'item7', 'key4': 'item8', 'key5': ['item1', 'item2', 'item3'], 'key6': 'item7'} i need remove duplicate values dictionary , replace them empty value (""). found couple solution on here working intended
for key, value in mydict.items(): if values not in key newdict.values(): mydict[key] = value else: mydict[key] = "" print newdict this removing values , outputting
# newdict:{key1: '', key2: '', key3: '', key4: '', key5: '', key6: '') i'm looking output be
# newdict = {'key1': '', 'key2':['item4', 'item5', 'item6'], 'key3': '', 'key4': 'item8', key5: ['item1', 'item2', 'item3'], 'key6': 'item7'}
you have right overall idea, there 3 problems code:
- you're storing values
mydictinstead ofnewdict. - on line 2, you're checking
valuesinstead ofvalue. - also on line 2,
keyshouldn't there, , throwssyntaxerror.
here correct code:
newdict = {} key, value in mydict.iteritems(): if value not in newdict.values(): newdict[key] = value else: newdict[key] = "" print newdict if you're not in anti-ternary operator camp, shorten this:
newdict = {} key, value in mydict.iteritems(): newdict[key] = value if value not in newdict.values() else "" print newdict or, if rather remove values original dict (mydict) instead of building new 1 (newdict), this:
foundvalues = [] key, value in mydict.iteritems(): if value not in foundvalues: foundvalues.append(mydict[key]) else: mydict[key] = "" print mydict if need duplicate values removed in specific order, check out ordereddicts.
update:
in light of updated requirements -- values removed original dict, starting beginning -- if you're able initialize mydict ordereddict instead of dict, need replace this:
mydict = {'key1': ['item1', 'item2', 'item3'], 'key2': ['item4', 'item5', 'item6'], 'key3': 'item7', 'key4': 'item8', 'key5': ['item1', 'item2', 'item3'], 'key6': 'item7'} with this:
from collections import ordereddict … mydict = ordereddict([('key1', ['item1', 'item2', 'item3']), ('key2', ['item4', 'item5', 'item6']), ('key3', 'item7'), ('key4', 'item8'), ('key5', ['item1', 'item2', 'item3']), ('key6', 'item7')]) and use same code provided above.
Comments
Post a Comment