[英]Update value of dictionary after iterating through list
I have the following:我有以下几点:
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
I am looking to loop through tup_list, and if the key exists in my_dict, I want to add +1 to the value associated with that key in my_dict.我希望遍历 tup_list,如果 my_dict 中存在键,我想将 +1 添加到 my_dict 中与该键关联的值。 I am getting errors and I am not sure how best to fix this.我收到错误,我不确定如何最好地解决这个问题。
You are getting error Because when you do :你收到错误因为当你这样做时:
for tup in tup_list:
if tup[0] in my_dict:
my_dict[0]+=1 #first check what you are increasing
Try to print(my_dict[0])
are you getting what you were expecting?尝试print(my_dict[0])
你得到你期望的结果了吗?
So you are increasing the value but where are you storing that changed stuff?所以你正在增加价值,但你在哪里存储改变的东西? For that, you have to tell dictionary to save that updated value of which key.为此,您必须告诉字典保存哪个键的更新值。
instead of :代替 :
my_dict[0]+=1
Use:用:
my_dict[tup[0]]+=1
or或者
my_dict[item[0]]=value+1 #if you are iterating over dict
Try this尝试这个
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))
Detailed solution:详细解决方案:
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))
output:输出:
{'name4': 1, 'name3': 0, 'name6': 1, 'name5': 0, 'name1': 1, 'name2': 0}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.