函数返回更新的字典

时间:2018-02-05 12:43:24

标签: python python-3.x

我正在学习字典 这是我的编码

def IncrementalCount(dict,a,b):

     dict={}.fromkeys(b,0)#creat dict initializing the count to each of "b" to 0 

     for txt in a:
          if txt in dict:
             dict[txt]+=1

     return (dict)        
counts={}
counts=IncrementalCount(counts,"{hello!{}","}{#")
print(counts)
counts=IncrementalCount(counts,"#Goodbye!}","}{#!@")
print(counts)

打印输出

{'}': 1, '{': 2, '#': 0}
{'}': 1, '{': 0, '#': 1, '!': 1, '@': 0}

但必须打印

{'}': 1, '{': 2, '#': 0}
{'}': 2, '{': 2, '#': 1, '!': 1, '@': 0}

请帮帮我

1 个答案:

答案 0 :(得分:0)

Resetting the counts to 0 was the problem with your code. So do not do dict={}.fromkeys(b,0) but just initialize the new keys. Something like this:

def IncrementalCount(my_dict,a,b):
     dict.update({k:0 for k in b if k not in my_dict})
     for txt in a:
          if txt in my_dict:
             my_dict[txt]+=1
     return my_dict

counts={}
counts=IncrementalCount(counts,"{hello!{}","}{#")
print(counts)  # {'}': 1, '{': 2, '#': 0}
counts=IncrementalCount(counts,"#Goodbye!}","}{#!@")
print(counts)  # {'}': 2, '{': 2, '#': 1, '!': 1, '@': 0}