简体   繁体   中英

Need to create a new dictionary from an existing dictionary in a different format in python

My original dictionary is dict1.

dict1={'Input.txt':'Randy','Code.py':'Stan','Output.txt':'Randy'}

I need the output as below

{'Randy':['Input.txt','Output.txt'],'Stan':['Code.py']}

Neat Python skills:

dict1 = {'Input.txt':'Randy','Code.py':'Stan','Output.txt':'Randy'}
out = {}
for k, v in dict1.items():
    out.setdefault(v, []).append(k)

giving the expected:

{'Randy': ['Input.txt', 'Output.txt'], 'Stan': ['Code.py']}

So we iterate over the key, value pairs in sync by unpacking the tuples returned from the dictionaries .items() method. For each pair, we set the value (ie 'Randy' , 'Stan' , 'Randy' ) as a key to a new list in the output dictionary if there is not already a list there - this is done neatly with the setdefault method.

Because the return value from setdefault will either be the new list we just created or the already populated list (in the case of the 'Output.txt' pair) and the fact that lists are mutable (changes to them affect all references to them), we can just append our key ( 'Input.txt' , 'Code.py' , 'Output.txt' ) straight to whatever is returned, new or old.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM