我是Python的新手,正在学习嵌套字典。下面是我的代码。
from header import read_data, VALID_AREAS
from collections import defaultdict
from collections import OrderedDict
from operator import itemgetter
def area_expenditure_counts(data, lower_spent, upper_spent):
for k,v in data.items():
areas = v["area"]
expend = v["expenditure"]
storage = defaultdict(list)
if areas and expend:
if (areas in VALID_AREAS):
{storage[d['area']].append(d['expenditure']) for _, d in data.items() if d['area']}
results = dict(storage)
output = {}
for k1,v1 in results.items():
if k1 in results.keys():
count = 0
for data in v1:
if data and (int(data) >= lower_spent) and (int(data) <= upper_spent):
count += 1
if lower_spent > upper_spent :
return 0
output[k1] = count
output1 = OrderedDict(sorted(output.items(),key=itemgetter(1), reverse=True))
#topfive = (output1.items()[:5])
return list(output1.items())[:5]
### HOW TO RETURN TOP 5 AREAS BY EXPENDIRUE IN DESCENDING ORDER AND IN ALPHABETICAL ORDER
我想以支出计数返回仅前5个区域的函数作为元组的列表[(area,支出_计数),...]。应按计数从高到低的顺序列出前5个区域,并按字母顺序将关系断开。我该如何删除上面的代码? 非常感谢您的帮助。