我有如下字典
sample = {'??': 2, 'N': 0, 'Y': 111, 'n': 0, 'n/a': 2, 'y': 55}
我希望输出如下
sample_op = {'??': 2, 'N': 0, 'Y': 166, 'n/a': 2}
答案 0 :(得分:0)
您可以尝试以下代码:
sample = {'??': 2, 'N': 0, 'Y': 111, 'n': 0, 'n/a': 2, 'y': 55}
samp_op = {}
for k, v in sample.items():
lowercase = k.lower()
if k!=lowercase and sample.has_key(lowercase):
samp_op[lowercase] = sample[lowercase] + v
else:
samp_op[k] = v
print samp_op
输出为:
{'??': 2, 'y': 166, 'n/a': 2, 'n': 0}
答案 1 :(得分:0)
您可以使用defaultdict:
from collections import defaultdict
sample = {'??': 2, 'N': 0, 'Y': 111, 'n': 0, 'n/a': 2, 'y': 55}
sample_op = defaultdict(int)
for (k,v) in sample.items():
sample_op[k.upper()] += v
print sample_op
打印:
defaultdict(<class 'int'>, {'??': 2, 'N': 0, 'Y': 166, 'N/A': 2})
答案 2 :(得分:0)
您应该使用dict comprehension和.get
方法:
sample = {'??': 2, 'N': 0, 'Y': 111, 'n': 0, 'n/a': 2, 'y': 55}
sample_op = {k.upper():sample.get(k.upper(),0)+v for k,v in sample.items()}
print(sample_op)
输出:
{'??': 4, 'N': 0, 'Y': 166, 'N/A': 2}
注意::如果您使用的是Python 2.6或更早版本,请使用:
sample = {'??': 2, 'N': 0, 'Y': 111, 'n': 0, 'n/a': 2, 'y': 55}
sample_op = dict((k.upper(), sample.get(k.upper(),0)+v) for (k, v) in sample.items())
print sample_op
输出:
{'??': 4, 'N': 0, 'Y': 166, 'N/A': 2}
发生了什么事?
借助 dict理解,您可以使用新规则构建dict
;即,如果您想从另一个dict
的每个值中加2来生成一个dict
,则可以:
new_dict = {k:v+2 for k,v in first_dict.items()}
或者-在我们的示例中-我们正在创建具有以下结构的dict
:
{k.upper(): # Key of our new dict: the uppercase of the old dict
sample.get(k.upper(),0)+v # We are asking for the value of our uppercase key in the old dict. If there's none, we assume as value 0. Then we add the value of the current key.
for k,v in sample.items()} # we iterate through all the key, value in our dict