dictionary - Extend dict from key/values pair to key/value pair in Python -


mydict = {'121': ['adrian', 'alex', 'peter'], '122': ['john', 'vic', 'bill']} 

i want 'extend' dictionary each key/value pair consists of 1 value, instead of list. tried iterating mydict.keys() , mydict.values() , construct new dict, didnt work out (i'm quite new python3). want achieve:

mynewdict = {'121': 'adrian', '121': 'alex', '121': 'peter', '122': 'john', '122': 'vic', '122':'bill'} 

based on comments above, here's how invert dict , allow multiple values each key:

from collections import defaultdict mynewdict = defaultdict(list) staff_id, names in mydict.items():     name in names:         mynewdict[name].append(staff_id) 

you might use defaultdict of set , add instead of list , append if order doesn't matter:

from collections import defaultdict mynewdict = defaultdict(set) staff_id, names in mydict.items():     name in names:         mynewdict[name].add(staff_id) 

Comments

Popular posts from this blog

javascript - how to protect a flash video from refresh? -

android - Associate same looper with different threads -

visual studio 2010 - Connect to informix database windows form application -