【发布时间】:2018-04-05 19:01:23
【问题描述】:
我有一个 python 字典,其中的值是 2 项列表。第一项是计算我看到钥匙的次数。第二项是另一个整数,我需要根据一些输入进行更新。
dictionary = {
'key1' : [1, 200]
'key2' : [1, 100]
}
假设,我再次遇到key1,输入是150。所以更新操作应该产生
dictionary = {
'key1' : [2, 350]
'key2' : [1, 100]
}
我该怎么做?我看到了this post,但没有帮助。请建议。我正在使用 Python 3。
编辑:
在发布之前,我尝试了以下内容:
data = defaultdict(list)
key = requestTokens[1] # one of the input that works as a key
data[key][0] +=1
data[key][1] += int(statusTokens[1]) #another input is statusTokens[1] a string
但我遇到了错误
data[key][0] +=1
IndexError: list index out of range
【问题讨论】:
-
你知道字典是如何工作的吗?如果没有,您应该查看文档。您可以就地修改列表和字典...
-
有什么问题?您需要做的就是添加一些数字。
-
@Aran-Fey 查看编辑
-
@ForceBru 查看编辑
标签: python python-3.x