所以这是我的问题,我有一个字典,其中包含以下键=>值:
6bc51fb21fd9eefef4ec97a241733cd59b71e8e14ad70e9068d32002:политичка -> 2
6bc51fb21fd9eefef4ec97a241733cd59b71e8e14ad70e9068d32002:државата -> 2
6bc51fb21fd9eefef4ec97a241733cd59b71e8e14ad70e9068d32002:енергично -> 1
1caa60ebf9459d9cd406f1a03e1719b675dcfaad78292edc7e4a56be:полициска -> 1
我有这段代码来显示所需的密钥:
for key, value in count_db.iteritems():
print key[:56]
所以现在我有:
6bc51fb21fd9eefef4ec97a241733cd59b71e8e14ad70e9068d32002 -> 2
6bc51fb21fd9eefef4ec97a241733cd59b71e8e14ad70e9068d32002 -> 2
6bc51fb21fd9eefef4ec97a241733cd59b71e8e14ad70e9068d32002 -> 1
1caa60ebf9459d9cd406f1a03e1719b675dcfaad78292edc7e4a56be -> 1
我需要将它们合并到:
6bc51fb21fd9eefef4ec97a241733cd59b71e8e14ad70e9068d32002 -> 5
1caa60ebf9459d9cd406f1a03e1719b675dcfaad78292edc7e4a56be -> 1
我已经做到了,但我没有成功地做到这一点:
length_dic=len(count_db.keys())
for key, value in count_db.iteritems():
count_element=key[:56]
#print "%s => %s" % (key[:56], value) #value[:56]
for i in range(length_dic):
i+=1
if count_element == key[:56]:
itr+=int(value)
print i
length_dic=length_dic-1
任何提示?
答案 0 :(得分:4)
一个简单的方法是:
result = {}
for key, value in count_db.iteritems():
result[key[:56]] = result.get(key[:56], 0) + value
如果你想在一行上获得它,你也可以用reduce
实现相同的目标:
import collections
result = reduce(lambda x,y: x[y[0][:56]] += y[1] , count_db.iteritems(), collections.defaultdict(int))
答案 1 :(得分:1)
将您的字典视为
>>> spam={"6bc51fb21fd9eefef4ec97a241733cd59b71e8e14ad70e9068d32002:AAAA": 2,
"6bc51fb21fd9eefef4ec97a241733cd59b71e8e14ad70e9068d32002:BBBB": 2,
"6bc51fb21fd9eefef4ec97a241733cd59b71e8e14ad70e9068d32002:CCCC": 1,
"1caa60ebf9459d9cd406f1a03e1719b675dcfaad78292edc7e4a56be:DDDD": 1
}
您可以在某种程度上执行以下操作
>>> bacon=collections.defaultdict(int)
>>> for k,v in [(k[:56],v) for k,v in spam.iteritems()]:
bacon[k]+=v
>>> bacon
defaultdict(<type 'int'>, {'6bc51fb21fd9eefef4ec97a241733cd59b71e8e14ad70e9068d32002': 5, '1caa60ebf9459d9cd406f1a03e1719b675dcfaad78292edc7e4a56be': 1})
>>>
答案 2 :(得分:0)
我不明白为什么你在代码中做了所有这些。我认为这样做可以做到:
tmp_dict = {}
for key, value in count_db.iteritems():
count_element=key[:56]
if count_element in tmp_dict:
tmp_dict[count_element] += value
else:
tmp_dict[count_element] = value
答案 3 :(得分:0)
这正是Counter对象(版本2.7+)的用途:
import collections
c = collections.Counter()
for key, value in count_db.iteritems():
c[key[:56]] += value