简体   繁体   中英

Add a value list for specific keys in dictionary (python 3.x)

I want to return a dictionary with capital letter as keys and a list small letters as values.

def sample(d):
    new_group = {}
    for small_letters, capitals in d.items():
        for capital in capitals:            
            new_group[capital] = [small_letters]
    return(new_group)

print(sample({"aaa":["A","B"], "bbb":["A","C"], "ccc":["A"]}))

My code returns:

{"A":["ccc"], "B":["aaa"], "C":["bbb"]}

Expected result:

{"A":["aaa","bbb","ccc"], "B":["aaa"], "C":["bbb"]}

You are re-writing the dictionary value, not appending to the list.

def sample(d):
    new_group = {}
    for small_letters, capitals in d.items():
        for capital in capitals:            
            new_group[capital] = new_group.get(capital, []) + [small_letters]
    return(new_group)

print(sample({"aaa":["A","B"], "bbb":["A","C"], "ccc":["A"]}))

Results:

{'A': ['aaa', 'bbb', 'ccc'], 'B': ['aaa'], 'C': ['bbb']}

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