captrap
captrap

Reputation: 65

Appending associative arrays in Python

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?

Upvotes: 3

Views: 21231

Answers (4)

zwol
zwol

Reputation: 140788

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]})

Upvotes: 14

Frédéric Hamidi
Frédéric Hamidi

Reputation: 263047

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

userData = data.setdefault(user, {})
userData[i] = {'item': row[0], 'time': row[1]}

Upvotes: 1

Hugh Bothwell
Hugh Bothwell

Reputation: 56684

import collections

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

Upvotes: 4

nmichaels
nmichaels

Reputation: 50999

If data[user] is a list, you can append to it with data[user].append({'item':row[0],'time':row[1]}).

Upvotes: 0

Related Questions