python - 将字典中的值替换为常量中的值

标签 python django list dictionary

我正在使用 Django,并且我有一个类来定义一些常量(我在我的模型中使用它)

class ArticleStatus:

  OPEN = 'open'
  CLOSED = 'closed'
  BLOCKED = 'blocked'

  CHOICES = (
    (OPEN, 'Open'),
    (CLOSED, 'Closed'),
    (BLOCKED, 'Blocked')  
  )

在我看来,我有一个查询集,它给了我这个结果:

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}
]

Working example

但是,我的代码看起来效率不是很高,我想问是否有人有更好的解决方案?

最佳答案

一种方法是使用 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}]}

关于python - 将字典中的值替换为常量中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50220182/

相关文章:

list - 如何在不使用列表模块的情况下编写 Erlang 的列表连接?

jquery - 使用 jQuery 在每 5 个 <li> 之后添加 </ul><ul>

python - PySpark:PicklingError:无法序列化对象:TypeError:无法 pickle CompiledFFI 对象

python - webbrowser.open() 断开链接(python 3.7)

python - 如何/应该如何在 Python/其他语言中管理跨包模块中的全局数据?

django - 使用JsonResponse分页

python - 在 Django Rest Framework 中发布外键 ID

php - Django 唯一 URL 重定向问题

python - 如何使 Anaconda python 在 Windows 上的 Emacs 中工作

list - 在序言中找到列表的所有 k 长度子集