Python 用常量中的值替换字典中的值
我正在使用Django,我有一个类来定义一些常量(我在模型中使用这个) 在我看来,我有一个查询集,它给出了以下结果:Python 用常量中的值替换字典中的值,python,django,list,dictionary,Python,Django,List,Dictionary,我正在使用Django,我有一个类来定义一些常量(我在模型中使用这个) 在我看来,我有一个查询集,它给出了以下结果: context['total'] = [ {'status': 'open', 'total': 102}, {'status': 'closed', 'total': 150}, {'status': 'blocked', 'total': 24} ] 我的目标是将状态值从常量转换为可读性更强的值。我是用下面的代码做的 for i in range(0, len(
context['total'] = [
{'status': 'open', 'total': 102},
{'status': 'closed', 'total': 150},
{'status': 'blocked', 'total': 24}
]
我的目标是将状态值从常量转换为可读性更强的值。我是用下面的代码做的
for i in range(0, len(context['total'])):
status = context['total'][i]['status']
for status_const in ArticleStatus.CHOICES:
if status == status_const[0]:
context['total'][i]['status'] = status_const[1]
转换后的结果是:
context['total'] = [
{'status': 'Open', 'total': 102},
{'status': 'Closed', 'total': 150},
{'status': 'Blocked', 'total': 24}
]
但是,我的代码看起来效率不高,我想问问是否有人有更好的解决方案?一种方法是使用
for
循环迭代列表,并使用预先计算的字典映射:
choice_map = dict(ArticleStatus.CHOICES)
for item in context['total']:
item['status'] = choice_map[item['status']]
print(context)
{'total': [{'status': 'Open', 'total': 102},
{'status': 'Closed', 'total': 150},
{'status': 'Blocked', 'total': 24}]}
这是我能想到的最短的:
CHOICES = {OPEN: 'Open',
CLOSED: 'Closed',
BLOCKED: 'Blocked'}
print([{'status': ArticleStatus.CHOICES[x['status']],
'total': x['total']} for x in context['total']])
你可以通过就地突变来减少它,但我总是喜欢一个清晰的功能性风格作为起点 哇,太好了,看起来干净多了。非常感谢!
CHOICES = {OPEN: 'Open',
CLOSED: 'Closed',
BLOCKED: 'Blocked'}
print([{'status': ArticleStatus.CHOICES[x['status']],
'total': x['total']} for x in context['total']])