提高多维字典循环效率

时间:2016-12-20 13:32:09

标签: python dictionary optimization

我正在使用python进行第一步并尝试迭代多维字典,同时检查密钥是否存在而不是None。 为了说清楚,代码有效!但我觉得应该有更好的方法来实现它:

for key in sites[website_name]: 
    if 'revenue' in sites[website_name][key]:
        if sites[website_name][key]['revenue'] is not None:
            totalSiteIncome += sites[website_name][key]['revenue']
        else:
            sites[website_name][key]['revenue'] = 0
    if 'spent' in sites[website_name][key]:
        if sites[website_name][key]['spent'] is not None:
            totalSiteSpent += sites[website_name][key]['spent']
        else:
            sites[website_name][key]['spent'] = 0

知道我是否以及如何改善循环?

请记住,在这里寻找最佳实践,thx!

3 个答案:

答案 0 :(得分:2)

发布sites[website_name]字典的样本确实会有所帮助,但如果我理解正确的话,我会这样做:

totalSiteIncome = sum(x.get('revenue', 0.0) for x in sites[website_name])
totalSiteSpent = sum(x.get('spent', 0.0) for x in sites[website_name])

如评论中所述,.get()允许您不关心密钥是否存在,并且如果不存在则采用默认参数(在本例中为0)。除此之外,只是sum()函数中的生成器。

在英语中,第一行是:

“如果我revenues词典中的每个网站都存在site并将其汇总,请将其全部归结。如果未记录revenue,则假设为0”

作为旁注,在您的代码中,totalSiteIncometotalSiteSpent也必须初始化,否则它将无法运行。在我的版本中,他们不必是,如果他们是他们的价值将被覆盖。

答案 1 :(得分:1)

如果您需要一个与目标字段(revenuespent)的嵌套级别无关的解决方案,则以下方法可能很有用。如果您想添加越来越多的字段也很有用,就像这个解决方案一样,您不需要为每个新字段重复代码。

除此之外,我的建议还有一些缺点,与你的解决方案相比:它使用的是递归性较低的可读性,还有一个标志(return_totals),感觉很烦人。只需将5美分加入头脑风暴。

import collections

def _update(input_dict, target_fields, totals = {}, return_totals=True):
    result = {}
    for k, v in input_dict.iteritems():
        if isinstance(v, dict):
            r = _update(input_dict[k], target_fields, totals, return_totals=False)
            result[k] = r
        else:
            if k in target_fields: 
                result[k] = input_dict[k] or 0
                if k not in totals:
                    totals[k] = 0
                totals[k] += result[k]
            else:
                result[k] = input_dict[k]
    if return_totals:
        return {
            'updated_dictionary': result,
            'totals': totals,
        }
    return result

new_sites = _update(input_dict = sites, target_fields = ['revenue', 'spent'])

print 'updated_dictionary:'
print new_sites['updated_dictionary']
print 'totals:'
print new_sites['totals']

答案 2 :(得分:0)

应使用迭代器方法迭代字典,例如dict.keys()dict.values()dict.items()

dict.keys():

d = {'a': '1', 'b': '2'}
for key in d.keys():
    print(key)

输出:

a
b

dict.values():

d = {'a': '1', 'b': '2'}
for value in d.values():
    print(value)

输出:

1
2

dict.items():

d = {'a': '1', 'b': '2'}
for key, value in d.items():
    print(key + " -> " + value)

输出:

a -> 1
b -> 2

注意:

这种方法在Python2和Python3中都有效,但在Python3中只是真正的迭代器(提高效率)。 Python2中的迭代器分别称为dir.iterkeys()dir.itervalues()dir.iteritems()