【问题标题】:Python Dictionary contains List as Value - How to update based on some other inputPython字典包含列表作为值-如何根据其他输入进行更新
【发布时间】: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


【解决方案1】:
>>> di = {'key1': [1,200], 'key2':[1,100]}
>>> di
{'key1': [1, 200], 'key2': [1, 100]}
>>> di['key1'][0] += 1
>>> di['key1'][1] += 150
>>> di
{'key1': [1, 300], 'key2': [1, 100]}
>>> 

所以看上面的例子,你可以看到它首先访问键,然后是数组中的索引,并将其设置为一个新值。 di['key1'][0] += 1 将其递增 1 di['key1'][1] += 150 正在添加新值

【讨论】:

  • 我在发布问题之前遵循了这种方法,但出现“列表索引超出范围”错误。请查看更新后的帖子
  • 你的数组初始化了吗? key = requestTokens[1] key 的值是你所期望的吗?
猜你喜欢
  • 2011-05-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-18
  • 1970-01-01
  • 2019-07-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多