Python在循环问题上动态增加字典

时间:2015-07-01 22:14:10

标签: python dictionary

我正在尝试做类似下面的事情。如果循环条件上的“If语句”匹配,我想使用“If”语句中的一个参数进行增量。

value = [0,1,2,3,4,5,6]
data = {'value': 3, 'foo': 'foo'}
for value in value:
    if (int(data['value']) == value and data['foo'] == 'foo'):
        findings_score[value] =  findings_score[value] + 1

我正在尝试在python上执行此操作,因为值 - “findings_score [value]”`需要初始化,我收到错误。我可以通过单独初始化discovery_score [value] dict来做到这一点,但我想在这里理解最好的方法。

`错误 - NameError:全局名称'findings_score [value]'未定义

2 个答案:

答案 0 :(得分:0)

听起来这就是你想要的:

values = [0,1,2,3,4,5,6]
findings_score = {}

data = {'value': 3, 'foo': 'foo'}

for value in values:
    if (int(data['value']) == value and data['foo'] == 'foo'):
        if value in findings_score:
            findings_score[value] =  findings_score[value] + 1
        else:
            findings_score[value] = 1

答案 1 :(得分:0)

使用defaultdict,在循环外初始化字典:

from collections import defaultdict
findings_score = defaultdict(int)
values = [0,1,2,3,4,5,6]

for value in values:
    if int(data['value']) == value and data['foo'] == 'foo':
        findings_score[value] += 1

使用普通的dict你可以使用dict.setdefault或dict.get:

findings_score = {}
values = [0,1,2,3,4,5,6]

for value in values:
    if int(data['value']) == value and data['foo'] == 'foo':
        findings_score[value] = findings_score.get(value, 0) + 1

findings_score = {}
values = [0,1,2,3,4,5,6]

for value in values:
    if int(data['value']) == value and data['foo'] == 'foo':
        findings_score.setdefault(value, 0)
        findings_score[value] += 1

如果您希望值中的所有元素都在输出中,您可以使用dict.fromkeys:

 findings_score = dict.fromkeys(values,0)
 for value in values:
     if int(data['value']) == value and data['foo'] == 'foo':
        findings_score[value] += 1