【问题标题】:Combine values from 2 different dictionaries in python在python中组合来自2个不同字典的值
【发布时间】:2020-10-20 19:55:52
【问题描述】:

例如,我有 2 个字典

dict1 = { 'a': 1, 'b': 2, 'c':3 }
dict2 = { 'a': 5, 'b': 6, 'c':7, 'd':8, 'e':9}

dicts 可以变化,有时 dict1 可能比 dict2 长。 这些 dicts 使用烧瓶传递到 html 页面。 神社代码如下

{% for key, value in dict1.items() %}
   <tr>
     <th>{{key}}</th>
     <td>{{value}}</td>
     <td>{{dict2.get(key,'0')}}</td>
   </tr>
{% endfor %}

上述dicts的输出如下

a   1   5
b   2   6
c   3   7

我怎样才能得到以下输出

a   1   5
b   2   6
c   3   7
d   0   8
e   0   9

如果 dict1 比 dict2 长,反之亦然。 我可以使用 jinja 来实现它,还是应该在 python 中计算并用最终结果呈现。如果必须在 python 中计算,我该怎么做?

【问题讨论】:

    标签: python-3.x dictionary flask iterator jinja2


    【解决方案1】:

    获取所有唯一键

    dict1 = { 'a': 1, 'b': 2, 'c':3 }
    dict2 = { 'a': 5, 'b': 6, 'c':7, 'd':8, 'e':9}
    
    keys = list(set((list(dict1.keys()) + list(dict2.keys()))))
    keys.sort()
    

    遍历键并获取值

    {% for key in keys %}
       <tr>
         <th>{{key}}</th>
         <td>{{dict1.get(key, 0)}}</td>
         <td>{{dict2.get(key, 0)}}</td>
       </tr>
    {% endfor %}
    

    【讨论】:

      猜你喜欢
      • 2016-11-18
      • 1970-01-01
      • 2019-08-03
      • 2017-09-18
      • 2022-11-03
      • 1970-01-01
      • 2017-04-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多