python - making a dictionary from another dictionary by searching keys -
i have dictionary looks this:
dictionary1={'orange':[red,yellow],'green':[blue,yellow],'purple'[red,blue]}
and want create new dictionary takes old 1 , turns like:
dictionary2={'red':[orange,purple],'blue':[green,purple],'yellow':[orange,green]}
so code should go through values, , create each 1 key old keys associated them set value (sorry wording's bit confusing)
this tried:
def makereversedictionary(): dictionary1 ={} dictionary1 = makedictionaryfromfile() dictionary2={} k, v in dictionary1.iteritems(): dictionary2.setdefault(v,[]).append(k) print (dictionary2)
and list objects unhashable
error. think might happening is trying assign each value key twice (eg. yellow,yellow:[orange,green]) impossible. i'm not sure how prepare it.
the list objects unhashable
error arises if seek , utilize whole list key. need iterate through list , utilize each item key.
dict1 = {'orange':['red','yellow'], 'green':['blue','yellow'], 'purple':['red','blue']} dict2 = {} k,vlist in dict1.iteritems(): # or dict1.items() in python3 v in vlist: dict2.setdefault(v,[]).append(k)
this produces dict2
as:
{'blue': ['purple', 'green'], 'yellow': ['orange', 'green'], 'red': ['orange', 'purple']}
edit:
an alternative setdefault
utilize defaultdict(list)
dict2
.
python dictionary
No comments:
Post a Comment