我正在迈出python的第一步,并尝试迭代多维字典,同时检查key是否存在而不是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
知道我是否可以以及如何改善循环吗?
请记住,在这里寻找最佳实践,谢谢!
发布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()
功能中的一个生成器。
在英文中,第一行应为:
"如果它们存在于我site
字典中的每个网站,请告诉我所有revenues
并将它们相加。如果未记录revenue
,则假设 0">
作为旁注,在您的代码中,totalSiteIncome
和totalSiteSpent
也必须初始化,否则它将无法运行。在我的版本中,它们不必是,如果它们是,它们的值将被覆盖。
如果您需要与目标字段(revenue
和spent
)的嵌套级别无关的解决方案,则以下方法可能很有用。如果要添加越来越多的字段,也可能很有用,因为使用此解决方案,您无需为每个新字段重复代码。
除此之外,与您的解决方案相比,我的建议也有一些缺点:它使用递归,可读性较差,还有一个标志(return_totals
),感觉很hack。只是将我的 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']
字典应该使用它们的迭代器方法进行迭代,例如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
字典项目():
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()
。