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

Time:12-29

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"]}

CodePudding user response:

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']}
  • Related