简体   繁体   English

更新列表中的词典

[英]Update dictionaries in a list

I think this will be a simple answer and I'm just missing something. 我认为这将是一个简单的答案,我只是遗漏了一些东西。 I have a list which contains several dictionaries. 我有一个包含几个词典的列表。 So for a simplified example the data structure is this: 因此,对于简化示例,数据结构如下:

acctList = [{'acctid' : '101'},{'acctid' : '102'}, {'acctid' : '103'}]

I want update the dictionaries in the list with a new value. 我想用新值更新列表中的字典。 but when I do something like this: 但是当我做这样的事情时:

acctList[0].update({'acctid' : 'aaa'})

ALL of the dictionaries in the list get updated with the new value instead of just the one at index 0. I know that lists also use update, so I'm not sure how to specify I'm trying to update the dictionary and not the list item. 列表中的所有字典都使用新值而不是索引0处的字典进行更新。我知道列表也使用更新,所以我不知道如何指定我正在尝试更新字典而不是项目清单。 Any ideas? 有任何想法吗? Thanks in advance! 提前致谢!

You need to create your dictionaries so that you have a unique dictionary in each index of the list, eg: 您需要创建词典,以便在列表的每个索引中都有一个唯一的词典,例如:

acctList = [dict(acctid=str(i)) for i in range(101, 104)]

and acctList is: 和acctList是:

[{'acctid' : '101'},{'acctid' : '102'}, {'acctid' : '103'}]

Then you can modify each one separately without affecting the others: 然后,您可以单独修改每个,而不影响其他人:

>>> acctList[0].update(dict(acctid='10101'))
>>> acctList
[{'acctid': '10101'}, {'acctid': '102'}, {'acctid': '103'}]

Explanation: 说明:

When you create a list where every index points to the same object, and that object is mutable, changing in one place affects the rest because they're all the same object: 当您创建一个列表,其中每个索引都指向同一个对象,并且该对象是可变的时,在一个地方进行更改会影响其余部分,因为它们都是相同的对象:

>>> l = [[]]*4
>>> l[0].append('foo')
>>> l
[['foo'], ['foo'], ['foo'], ['foo']]

Since integers are immutable, you can do the following: 由于整数是不可变的,因此您可以执行以下操作:

>>> l = [0]*4
>>> l
[0, 0, 0, 0]
>>> l[0]+=1
>>> l
[1, 0, 0, 0]

In Python, mutable objects are sometimes used to hold and increment on integers when you need a pointer that can't change, and so you can't use a plain integer. 在Python中,当您需要一个无法更改的指针时,可变对象有时用于保持和递增整数,因此您不能使用普通整数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM