[英]How to add value for each specific key in python dictionary? (do not update another key)
In my case, I have a dictionary like this就我而言,我有一本这样的字典
dic_ = {'btcusd': [-1.0, -1.0],
'usdjpy': [-1.0, -1.0]}
For example, I would like to update the key 'usdjpy', I using this code例如,我想更新密钥“usdjpy”,我使用此代码
dic_['usdjpy'].append(1)
However, It updates all other keys in this dictionary and gives the result like但是,它会更新此字典中的所有其他键并给出如下结果
{'btcusd': [-1.0, -1.0, 1],
'usdjpy': [-1.0, -1.0, 1]}
So how to solve this problem?那么如何解决这个问题呢?
My desire result is as below我的愿望结果如下
{'btcusd': [-1.0, -1.0],
'usdjpy': [-1.0, -1.0, 1]}
The issue is during the initialization of your dictionary.问题出在字典初始化期间。 Do check, the id's for both the list are same.
请检查,两个列表的 id 相同。 ie the memory in which both the list are is same.
即两个列表相同的 memory。
> id('btcusd') == id('usdjpy')
True
To replicate this issue, Here I have initialized the an list for a,b为了复制这个问题,我在这里初始化了 a,b 的列表
> list = ['a','b']
> dic_ = dict.fromkeys(list, [-1.0,1.0])
> dic_['a'] is dic['b']
True
You can use list comprehension for sorting the issue您可以使用列表推导对问题进行排序
> dic_ = {key: [-1.0,1.0] for key in list}
> dic_['a'] is dic_['b']
False
Just in your case, the issue is your initialization:就您而言,问题在于您的初始化:
dict_ = dict(zip(symbol_list, [list()]*len(symbol_list)))
Just for a demo on [list()]*len(symbol_list)
,只是为了
[list()]*len(symbol_list)
上的演示,
> l = [['a']]*3
[['a'], ['a'], ['a']]
> for i in l:
> print(id(i), end=' : ')
139970284317824 : 139970284317824 : 139970284317824
The root of this problem comes from the way I define the dictionary.这个问题的根源在于我定义字典的方式。 Like @yatu comment under my post.
喜欢我帖子下的@yatu评论。 For example, If I generate the dictionary like this
例如,如果我像这样生成字典
symbol_list = ['a', 'b, 'c', 'd']
dict_ = dict(zip(symbol_list, [list()]*len(symbol_list)))
Then append using normal .append()
method.然后 append 使用普通的
.append()
方法。 It will append for all value-list in this dict_
对于此字典中的所有值列表,它将为
dict_
But if creating the dict_
in another way like但是如果以另一种方式创建
dict_
symbol_list = ['a', 'b', 'c', 'd']
dict_ = {}
for x in range(0, len(symbol_list)):
dict_[symbol_list[x]]= list()
then the append()
method will work as desired然后
append()
方法将按需要工作
The reason is answered in detail in this post: List of lists changes reflected across sublists unexpectedly原因在这篇博文中有详细解答: List of lists changes reflect across sublists unexpectedly
there must be something else that you're doing to get this result.为了得到这个结果,你必须做其他事情。 I tried it and it works just fine
我试过了,效果很好
dic_ = {'btcusd': [-1.0, -1.0],
'usdjpy': [-1.0, -1.0]}
dic_['usdjpy'].append(1)
print(dic_)
output output
{'btcusd': [-1.0, -1.0], 'usdjpy': [-1.0, -1.0, 1]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.