我试图遍历查询集并为每个项创建字典,然后将每个字典添加到列表中。我需要检查字典是否存在,然后更新值。我的问题是我不知道如何按金额值对列表进行排序。
也许这不是创建dicts的最佳方式?
这是我的代码:
#Create list
my_list_of_dicts = []
#Create dict object
my_dict = {}
#Find every user in query_set
for item in query_set: #query_set is a list of objects from a Django query: <QuerySet [<User: name123>, <User: name123>, <User: name456>, <User: name789>,]>
if item.name in my_dict:
#Update object
my_dict[item.name]['amount'] += item.amount
else:
#Create object
my_dict[itemrecruiter] = {'amount': item.amount, 'not-important' item.foo}
#Add dict to list
recruiters.append(my_dict)
print(my_list_of_dicts)
>>> [{"name123": {"amount": 8, 'not-important': 'foo123'}, "name456": {"amount": 3, 'not-important': 'foo456'}, "name789": {"amount": 20, 'not-important': 'foo789'}}]
答案 0 :(得分:1)
假设dict_
是列表中的字典变量(此处为a[0]
),您可以这样做:
import operator
output = sorted(dict_.items(), key = lambda x : x[1]['amount'])
输出:
[('name456', {'amount': 3}), ('name123', {'amount': 8}), ('name789', {'amount': 20})]
答案 1 :(得分:0)
为什么要使用将字典添加到列表中时只需保存一个值,您可能只会使代码更复杂。试试这个,看看它是否适合你
# Create dictionary here
my_dict = {}
# Query from db
for item in query_set:
if item.name in my_dict: # If the item already exist in the dictionary
my_dict[item.name] += item.amount # just update the amount
else: # If the item does exit in the dictionary then create it
my_dict[item.name] = item.amount
>>>print my_dict
{"name123": 8, "name456": 3, "name789": 20}
>>>my_dict["name123"]
8
你总是可以像这样循环你的字典
>>>>for key in my_dict:
print key,":", my_dict[key]
name123 : 8
name456 : 3
name789 : 20