Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

loops

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?

like image 996
Isabella Wilcox Avatar asked Feb 25 '15 01:02

Isabella Wilcox


3 Answers

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!

like image 76
Rachel Sanders Avatar answered Oct 14 '22 07:10

Rachel Sanders


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.

like image 36
Slater Victoroff Avatar answered Oct 14 '22 06:10

Slater Victoroff


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.

like image 42
deadbeef404 Avatar answered Oct 14 '22 06:10

deadbeef404