1

If I have, for example, a dictionary d and I want to add the value v - amongst possibly more of them in a list - to the key k, I usually do it this way:

if k in d:
    d [k].append (v)

else:
    d [k] = [v]

Is there a more elegant way, e.g. like

list_append (d [k],  v)

? The problem occurs for me mainly at dictionaries but a solution should not be restricted to them.

1 Answers1

0

Use setdefault:

d.setdefault(k, []).append(v)
U13-Forward
  • 69,221
  • 14
  • 89
  • 114