How to append to Python list in a dict without having to initialize the list? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How to append to Python list in a dict without having to initialize the list? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

In PHP, I can do this

$a['name'][] = 'el1';

In Python, I have to do this:

a = {}
a['name'] = []
a['name'].append('el1')

The problem with the above approach is that I’m losing the value of a['name'] in the next loop when iterating because I’m reinitializing a['name'] to an empty list .

Is there any way to append items to a list without having to initialize with an empty list first?

Answer

You can use the defaultdict module:

from collections import defaultdict
a = defaultdict(list)

With this setting, the module initializes to an empty list on first access, so you can just do:

 a['name'].append('el1')

and not worry about it.

Hope that helps!

We are here to answer your question about How to append to Python list in a dict without having to initialize the list? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji