Dict.setdefault (key, []). append () & # 8594; get rid of the extra list

How can I prevent a list from being added to a list when using setdefault with a list type definition.

output = dict()
output.setdefault("key", []).append(["name", 1])
print output
>>> {'key': [['name', 1]]}

      

Desired output

>>> {'key': ['name', 1]}

      

+3


source to share


1 answer


You want .extend

, not .append

- the former adds a list of items to the list, the latter adds one item - so if you pass a list to it, it will add the list as one sub-item.



+6


source







All Articles