组数据结构中的值

时间:2022-09-06 17:11:11

I'm pretty new to the world of Django / Python.

我是Django / Python世界的新手。

I have a the following query in a manager :

我在经理中有以下查询:

listOfHeroes = self.all().values('user__user__username','skill','level')

It return a table like this:

它返回一个这样的表:

[{'user__user__username': u'Aragorn', 'skill': 'Fireball', 'level': 5}, {'user__user__username': u'Leonidas', 'skill': 'sword', 'level': 1},{'user__user__username': u'Aragorn', 'skill': 'sword', 'level': 4},....]

I want to group my data by heroes. I mean Aragorn has two skills Fireball and Sword :

我想按英雄分组我的数据。我的意思是阿拉贡有两种技能火球和剑:

User: Aragorn / Skills: { sword level 4 / fireball level 5}

Final datas I have where skills are grouped by User must be easily iterable.

我有技能按用户分组的最终数据必须易于迭代。

If you have any ideas... I've tried to create a dictionary but I failed..

如果你有任何想法...我试图创建一个字典,但我失败了..

1 个解决方案

#1


0  

If you don't want to change your database query, use this:

如果您不想更改数据库查询,请使用以下命令:

result = {}
for item in listOfHeroes:
    if item['user__user__username'] not in result:
        result[item['user__user__username']] = []
    result[item['user__user__username']].append({'skill': item['skill'], 'level': item['level']})

for key, value in result.items():
    print 'User: {0} / Skills: {{ {1} }}'.format(key, ' / '.join(['{0} level {1}'.format(skill['skill'], skill['level']) for skill in value]))

#1


0  

If you don't want to change your database query, use this:

如果您不想更改数据库查询,请使用以下命令:

result = {}
for item in listOfHeroes:
    if item['user__user__username'] not in result:
        result[item['user__user__username']] = []
    result[item['user__user__username']].append({'skill': item['skill'], 'level': item['level']})

for key, value in result.items():
    print 'User: {0} / Skills: {{ {1} }}'.format(key, ' / '.join(['{0} level {1}'.format(skill['skill'], skill['level']) for skill in value]))