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
  • 5,944
  • 7
  • 38
  • 85

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
  • 3,870
  • 4
  • 22
  • 41