将dicts列表映射到dicts列表的dict中

时间:2015-09-23 13:56:20

标签: python list python-2.7 dictionary

我甚至不确定该怎么称呼它,所以搜索起来很困难。我有,例如,

<p:dataTable id="tbl" var="product" value="#{bean.productList}">
<p:column>
    <f:facet name="header">
       <h:outputText value="Product" />
    </f:facet>
    <h:outputText value="#{product.name}" />
    <f:facet name="footer">
        <h:outputText value="Total" />
    </f:facet>
</p:column>

<p:column>
    <f:facet name="header">
       <h:outputText value="Price" />
    </f:facet>
    <h:outputText value="#{product.price}" />
    <f:facet name="footer">
        <h:outputText value="#{bean.totalPrice}" />
    </f:facet>
</p:column>

</p:dataTable>

  <h:commandLink>
            <p:graphicImage name="/demo/images/pdf.png" />
            <p:dataExporter type="pdf" target="tbl" fileName="products" />
  </h:commandLink>

我想要像

这样的东西
people = [
    {"age": 22, "first": "John", "last": "Smith"},
    {"age": 22, "first": "Jane", "last": "Doe"},
    {"age": 41, "first": "Brian", "last": "Johnson"},
]

在Python 2中最干净的方法是什么?

2 个答案:

答案 0 :(得分:6)

只需循环并添加到新词典:

people_by_age = {}
for person in people:
    age = person.pop('age')
    people_by_age.setdefault(age, []).append(person)

dict.setdefault() method或者返回给定键的现有值,或者如果缺少键,则使用第二个参数首先设置该键。

演示:

>>> people = [
...     {"age": 22, "first": "John", "last": "Smith"},
...     {"age": 22, "first": "Jane", "last": "Doe"},
...     {"age": 41, "first": "Brian", "last": "Johnson"},
... ]
>>> people_by_age = {}
>>> for person in people:
...     age = person.pop('age')
...     people_by_age.setdefault(age, []).append(person)
... 
>>> people_by_age
{41: [{'last': 'Johnson', 'first': 'Brian'}], 22: [{'last': 'Smith', 'first': 'John'}, {'last': 'Doe', 'first': 'Jane'}]}
>>> from pprint import pprint
>>> pprint(people_by_age)
{22: [{'first': 'John', 'last': 'Smith'}, {'first': 'Jane', 'last': 'Doe'}],
 41: [{'first': 'Brian', 'last': 'Johnson'}]}

答案 1 :(得分:2)

使用defaultdict方法和dictonary.pop method

<强>代码:

from collections import defaultdict

people = [
    {"age": 22, "first": "John", "last": "Smith"},
    {"age": 22, "first": "Jane", "last": "Doe"},
    {"age": 41, "first": "Brian", "last": "Johnson"},
]

d = defaultdict(int)

people_dic = defaultdict(list)
for element in people:
    age = element.pop('age')
    people_dic[age].append(element)

print(people_dic)

<强>输出:

defaultdict(<type 'list'>, {41: [{'last': 'Johnson', 'first': 'Brian'}], 22: [{'last': 'Smith', 'first': 'John'}, {'last': 'Doe', 'first': 'Jane'}]})