我有一个名为“high_low_teams_in_profile”的嵌套字典,如下所示:
{
m_profile1:
{
team_size1:
{
low: 1,
high: 1
},
team_size2:
{
low: 1,
high: 1
}
},
m_profile2:
{
team_size1:
{
low: 1,
high: 1
},
team_size2:
{
low: 1,
high: 1
}
}
}
我想得到{m_profile1:4,m_profile2:4}
在python中最有说服力的方法是什么? 现在我有以下内容:
new_num_teams_in_profile = {}
for profile in high_low_teams_in_profile:
new_num_teams_in_profile[profile]= dict((team_size, sum(high_low_teams_in_profile[profile][team_size].values())) for team_size in high_low_teams_in_profile[profile])
new_num_teams_in_profile= dict((profile, sum(new_num_teams_in_profile[profile].values())) for profile in new_num_teams_in_profile)
答案 0 :(得分:2)
我不确定我是否说它是最Pythonic,但它是functional最多的:
p = high_low_teams_in_profile
{ prof:sum(p[prof][team][hl]
for team in p[prof]
for hl in p[prof][team])
for prof in p}
sum
的论点是generator expression,外{ prof:sum(...) for prof in p}
是dictionary comprehension。
答案 1 :(得分:0)
虽然这可能不是最pythonic,但以下代码应该可以工作,并且比原始版本更具可读性。请注意iteritems()
方法,它允许访问dict的键和值,而itervalues()
,顾名思义,只迭代dict的值。
final = {}
for key, sizes in high_low_teams_in_profile.iteritems():
total = 0
for value in sizes.itervalues():
s = sum(value.itervalues())
total += s
final[key] = total
print final
此外,您可以使用以下内容。虽然行数较短,但阅读起来稍微困难一些。
final = {}
for key, sizes in high_low_teams_in_profile.iteritems():
total = sum([sum(value.itervalues()) for value in sizes.itervalues()])
final[key] = total
print final