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?
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!
So, the way that you've phrased it no, you can only append
to something that exists. That said, you don't have to append to this at all, you could do this:
a = {'name': ['el1']}
No need to manually create your structure like that.
If you want to check for the existence of a key before trying to append to a list you can do this:
a.setdefault('name', []).append('el1')
The second argument to get
also gives you a default, saying if name
doesn't exist, append to an empty list instead.
I think you're asking for something like this:
a = {}
if 'name' not in a:
a['name'] = []
a['name'].append('el1')
Also, you might want to look at Python's defaultdict datatype to see if that would be better for your purposes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With