Python dict问题。如何分组相似的字符串?

时间:2011-01-18 21:37:28

标签: python django

for i in names:
    dict[i] = {'firstname': name[i]['firstname'],
               'lastname': name[i]['lastname']}
    print dict[0]['firstname'] # John
    print dict[0]['lastname'] # Doe

    # group similar lastnames, along with their firstnames
    # ...
return render_to_response('index.html', dict)

我想将以相似姓氏结尾的名称分组。 例如,输出应为:

<html>
  <body>
    <h1> Doe </h1>
    <p> John, Jason, Peter </p>

    <h1> Avery </h1>
    <p> Kelly, Brittany </p>
  </body>
</html>

'h1'标签应包含姓氏,'p'标签包含名字。

我该怎么做?

2 个答案:

答案 0 :(得分:6)

你的意思是这样的:

import collections

data = [
    {'firstname': 'John', 'lastname': 'Smith'}, 
    {'firstname': 'Samantha', 'lastname': 'Smith'}, 
    {'firstname': 'shawn', 'lastname': 'Spencer'},
]

new_data = collections.defaultdict(list)

for d in data:
    new_data[d['lastname']].append(d['firstname'])

print new_data

输出:

defaultdict(<type 'list'>, {'Smith': ['John', 'Samantha'], 'Spencer': ['shawn']})
模板中的

执行:

{% for lastname, firstname in data.items %}
    <h1> {{ lastname }} </h1>
    <p> {{ firstname|join:", " }} </p>
{% endfor %}

输出:

<h1> Smith </h1>
<p> John, Samantha </p>

<h1> Spencer </h1>
<p> shawn </p>

答案 1 :(得分:1)

您可以在对名称进行排序后使用groupby。你可以在这里看到它:http://docs.python.org/library/itertools.html#itertools.groupby