【问题标题】:How to extract multiple values of a list of python dictionary (i.e. extract all the values for one key)?如何提取python字典列表的多个值(即提取一个键的所有值)?
【发布时间】:2013-03-28 19:39:11
【问题描述】:

我的字典是这样的。

m_dict = {}  
m_dict.setdefault(ekey1, []).append(m_name)  
m_dict.setdefault(ekey2, []).append(u_r)  
m_dict.setdefault(ekey3, []).append(quan)  
m_dict.setdefault(ekey4, []).append(u_u)  
m_dict.setdefault(ekey5, []).append(r_r)  
m_dict.setdefault(ekey6, []).append(pr)

每个键都有多个值,即值作为项目列表附加。

我的问题是如何分别提取单个键的每个列表值?

例如ekey5 的值如下:

[a', Decimal('80'), Decimal('80'), u', Decimal('0'), Decimal('0.95')]

那么如何在单独的行中提取ekey5 的每个值?

然后如何在 django 模板中显示呢?

【问题讨论】:

  • 您还可以以更简单的方式将您的项目添加到字典中。 m_dict['ekey1'] = [1, 2, 3, ...] 可以循环执行。
  • 是的,我知道,但我正在从数据库中获取这些项目,然后放入 dict。这就是为什么这样做。这只是我整个事情的一部分。感谢您的帮助。

标签: python list dictionary django-templates


【解决方案1】:

在 Django 模板中执行此操作应该与基于 answers to this question 的等效 Python 非常相似

以下内容应与garmoncheg's answer相同

{% for key, value in m_dict.items %}
    {% for item in value %}
        {{ item }}
    {% endfor %}
{% endfor %}

【讨论】:

  • 是的,我已经尝试过了,效果很好!多谢。 :)
猜你喜欢
  • 2021-09-17
  • 1970-01-01
  • 2021-09-26
  • 2017-06-26
  • 1970-01-01
  • 2023-01-15
  • 2021-09-03
  • 2019-01-22
  • 1970-01-01
相关资源
最近更新 更多