如果我有字典
dict = {'brown dogs':3, 'dog of white':4, 'white cats':1, 'white cat':9}
我如何
a)搜索关键子串
b)对所选择的值进行求和
所以我得到了结果:
('dog', 7) and ('cat', 10)
答案 0 :(得分:3)
您可以使用collections.Counter
。
from collections import Counter
d = {'brown dogs':3, 'dog of white':4, 'white cats':1, 'white cat':9}
substrings = ['dog', 'cat']
counter = Counter()
for substring in substrings:
for key in d:
if substring in key:
counter[substring] += d[key]
print(counter.items())
<强>输出:强>
[('dog', 7), ('cat', 10)]
答案 1 :(得分:2)
使用字典保存潜艇:
dict = {'brown dogs':3, 'dog of white':4, 'white cats':1, 'white cat':9}
subs={'dog':0,'cat':0}
for sub in subs.keys():
for k,v in dict.items():
if sub in k:
subs[sub]+=v
print(subs)->{'dog': 7, 'cat': 10}
但如果您想自动猜测子键,可能会更难xD!
答案 2 :(得分:1)
这是另一种解决方案:
d = {'brown dogs':3, 'dog of white':4, 'white cats':1, 'white cat':9}
substrings = ['dog', 'cat']
my_list = [(substr, sum([d[key] for key in d.iterkeys() if substr in key])) for substr in substrings]
print my_list
<强>输出强>
[('dog', 7), ('cat', 10)]
答案 3 :(得分:0)
我会对它采取行动,因为我需要练习!
mydict = {'brown dogs':3, 'dog of white':4, 'white cats':1, 'white cat':9}
mykeys = ['dog', 'cat', 'rhino']
sums_dict = {}
for mkey in mykeys:
for dkey in mydict.keys():
if mkey in dkey:
try:
sums_dict[mkey] += mydict[dkey]
except KeyError:
sums_dict[mkey] = mydict[dkey]
print(sums_dict)