我在python非常新手,我目前正在学习这门语言。我发现数组(关联数组)被称为python中的字典({}) 我正面临一个问题。我需要建立一个字典并在for
循环中更新它。我的代码如下。Python更新字典到字典
loc = {}
result = { I get the list of records from database here, which has id and status }
for res in result:
temp={}
temp['id']= res.id
temp['status'] = res.status
loc.update(temp) # this replaces the values every time, i want append
print loc
下面
是我所期望的结果:
loc = { {'id' : 123 , 'status' : 'available' },
{ 'id' : 456 , 'status' : 'unavailable'}
}
有人可以帮助我。我尝试过:
loc = [] # [] this works with loc.append(temp)
this gives result as :
[{'id' : 123 , 'status' : 'available'},{'id' : 456 , 'status' : 'unavailable'}]
但我需要上面的结果与字典在Python中的字典。
您预期的结果'loc'不是字典,因为它不包含键和值。在一个词典的字典中,你的键值是字典。你打算用什么作为钥匙?为什么'loc'需要成为词典的词典?如您的底部结果所示,一系列的字典似乎正常工作。 – MattDMo
字典是一个键值对(由关键字索引)。现在外字典的关键是什么? – SuperSaiyan
为什么loc是一本字典? –