Appending associative arrays in Python

16,572

Solution 1

Something like this should work. Note that unlike PHP, Python has separate primitive types for numeric arrays (called "lists") and associative arrays (called "dictionaries" or "dicts").

if user not in data:
    data[user] = []
data[user].append({'item': row[0], 'time': row[1]})

Solution 2

import collections

data = collections.defaultdict(list)
for user,row,time in input:
    data[user].append({'row':row, 'time':time})

Solution 3

You can also use setdefault() and do something like:

userData = data.setdefault(user, {})
userData[i] = {'item': row[0], 'time': row[1]}
Share:
16,572
captrap
Author by

captrap

Updated on June 17, 2022

Comments

  • captrap
    captrap almost 2 years

    I've been all over looking for a solution to this recently, and so far to no avail. I'm coming from php to python, and running into an associative array difference I'm not sure now to overcome.

    Take this line:

    data[user]={i:{'item':row[0],'time':row[1]}}
    

    This overwrites each of my data[user] entries, obviously, as it's not appending, it's just replacing the data each time.

    In php if I wanted to append a new bit of data in a for loop, I could do

    data[user][i][]=array('item'=>'x','time'=>'y'); // crude example
    

    In python, I can't do:

    data[user][]={i:{'item':row[0],'time':row[1]}}
    

    It barfs on my []

    I also can't do:

    data[user][i]={'item':row[0],'time':row[1]}
    

    where I is my iterator through the loop... and I think it's because the data[user] hasn't been defined, yet, as of the operating? I've created the data={}, but I don't have it populated with the users as keys, yet.

    In python, do I have to have a key defined before I can define it including a sub-key?

    I've tried a bunch of .append() options, and other weird tricks, but I want to know the correct method of doing this.

    I can do:

    data[user,i]={'item':row[0],'time':row[1]}
    

    but this isn't what I want.

    What's my proper method here, python friends?