'python dictionary looping over multiple values and returning them as single list values for single key [closed]

names={"animal":"cat","animal":"dog","animal":"rat","bird":"humming"}
names_dict={}
for k,v in names.items():
    names_dict.setdefault(k,[]).append(v)   
print (names_dict)

My desired output should be:

{'animal': ['rat','cat','dog'], 'bird': ['humming']}

but the output im getting is this

{'animal': ['rat'], 'bird': ['humming']}

Can someone tell me what I am doing wrong?



Solution 1:[1]

This line:

names={"animal":"cat","animal":"dog","animal":"rat","bird":"humming"}

is exactly the same with this:

names={"animal":"rat","bird":"humming"}

When you add items to dict, if the key is already is in the dict, the value will be overridden.

Solution 2:[2]

As mentioned in @Vijay M's answer, the key in python dictionaries should be unique. I guess you are looking for a solution like this one:

names = {"cat": "animal", "dog": "animal", "rat": "animal", "humming": "bird"}

names_dict={}
for k, v in names.items():
    names_dict.setdefault(v,[]).append(k)

print(names_dict)

Note that the values and the keys are swapped.

Hopefully, this helps.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mehrdad Pedramfar
Solution 2 agastalver