开发者

Python dict question. How to group similar strings?

开发者 https://www.devze.com 2023-02-05 04:12 出处:网络
for i in names: dict[i] = {\'firstname\': name[i][\'firstname\'], \'lastname\': name[i][\'lastname\']} print dict[0][\'firstname\'] # John
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)

I want to group names that end with similar last-names. For example, the output should be:

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

    开发者_如何学Go<h1> Avery </h1>
    <p> Kelly, Brittany </p>
  </body>
</html>

The 'h1' tags are supposed to contain the last-names and the 'p' tags the first-names.

How should I do this?


You mean something like this:

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

Output :

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

in your template do:

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

output:

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

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


You may also use groupby after you have sorted the names. You can see it here: http://docs.python.org/library/itertools.html#itertools.groupby

0

精彩评论

暂无评论...
验证码 换一张
取 消