Skip to main content
 首页 » 编程设计

python之在 Python 中 append 关联数组

2025年05月04日23mayingbao

我最近一直在寻找解决这个问题的方法,但到目前为止无济于事。我从 php 转到 python,遇到了一个我现在不确定要克服的关联数组差异。

走这条线:

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

这会覆盖我的每个 data[user] 条目,显然,因为它不是 append 的,它只是每次都替换数据。

在 php 中,如果我想在 for 循环中追加一点新数据,我可以这样做

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

在 python 中,我不能这样做:

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

它呕吐在我的[]

我也做不到:

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

我是循环中的迭代器...我认为这是因为 data[user] 尚未定义,但在操作时?我已经创建了 data={},但我还没有用用户作为键来填充它。

在 python 中,是否必须先定义键才能定义它,包括子键?

我已经尝试了一堆 .append() 选项和其他奇怪的技巧,但我想知道执行此操作的正确方法。

我可以做:

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

但这不是我想要的。

Python friend 们,我这里的正确方法是什么?

请您参考如下方法:

像这样的东西应该可以工作。请注意,与 PHP 不同,Python 具有用于数值数组(称为“列表”)和关联数组(称为“字典”或“dict”)的单独原始类型。

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