【问题标题】:Update value of dictionary after iterating through list遍历列表后更新字典的值
【发布时间】:2018-04-12 20:31:28
【问题描述】:

我有以下:

tup_list=[("name1",2,3),("name6",54,6),("name4",4,6)]

my_dict={"name1": 0,"name2": 0,"name3": 0,"name4": 0,"name5": 0,"name6": 0}


def checker(tup_list,my_dict):
    for tup in tup_list: 
       if tup[0] in my_dict: 
          my_dict[0]+=1

我正在寻找循环遍历 tup_list,如果键存在于 my_dict 中,我想将 +1 添加到与 my_dict 中该键关联的值。我遇到了错误,我不确定如何最好地解决这个问题。

【问题讨论】:

  • 您的问题并没有明确说明。此外,您应该格式化您的代码。
  • 听起来好像您正在寻找其他人来遍历此列表...您尝试过什么?
  • 那么.. 到目前为止你写过什么尝试或代码吗?
  • 欢迎来到 StackOverflow。请阅读并遵循帮助文档中的发布指南。 Minimal, complete, verifiable example 适用于此。在您发布 MCVE 代码并准确描述问题之前,我们无法有效地帮助您。我们应该能够将您发布的代码粘贴到文本文件中并重现您描述的问题。 “我收到错误”不是问题规范。

标签: python dictionary for-loop tuples


【解决方案1】:

你得到错误因为当你这样做时:

for tup in tup_list: 
   if tup[0] in my_dict: 
      my_dict[0]+=1  #first check what you are increasing

试试print(my_dict[0]),你得到了你所期望的吗?

所以你正在增加价值,但你在哪里存储改变的东西?为此,您必须告诉字典保存哪个键的更新值。

而不是:

  my_dict[0]+=1

用途:

my_dict[tup[0]]+=1

my_dict[item[0]]=value+1   #if you are iterating over dict 

试试这个

def checker(tup_list,my_dict):
    for tup in tup_list:
        if tup[0] in my_dict:
            my_dict[tup[0]]+=1
    return my_dict

print(checker(tup_list,my_dict))

详细解决方案:

tup_list=[("name1",2,3),("name6",54,6),("name4",4,6),]

my_dict={"name1": 0,"name2": 0,"name3": 0,"name4": 0,"name5": 0,"name6": 0}


    def checker(tup_list,my_dict):
        for item in tup_list:
            for key,value in my_dict.items():
                if item[0]==key:
                    my_dict[item[0]]=value+1
        return my_dict

print(checker(tup_list,my_dict))

输出:

{'name4': 1, 'name3': 0, 'name6': 1, 'name5': 0, 'name1': 1, 'name2': 0}

【讨论】:

  • 谢谢。这很有帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-29
相关资源
最近更新 更多