0

Currently, in order to do what I'm describing, I have a code like this:

if key in dict:
    dict[key].append(item)
else:
    dict[key] = [item]

Is there any way I can append to list within dictionary without doing the explicit check?

Can this be done using another data structure?

What I need to do is to track all the items that have some parameter equal.

Karlovsky120
  • 6,212
  • 8
  • 41
  • 94

1 Answers1

0
d = {}    
d.setdefault(1, []).append('item')

in python .get used to retrieve key and optional argument to get if value not exist, however it will give you only initial value. whereas in .setdefault you will get a value for corresponding key or else it will initialise key with default value passed as another argument

Gahan
  • 4,075
  • 4
  • 24
  • 44