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