Python 函数返回更新的字典
我在学字典 这是我的代码Python 函数返回更新的字典,python,python-3.x,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=Incre
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}
请帮助我将计数重置为0是代码的问题。所以不要执行dict={}.fromkeysb,0,而只是初始化新键。大概是这样的:
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}
但是您正在将密钥重置为0。为什么不呢?它有什么问题?@siva请将答案标记为正确,因为它解决了您的问题