2017-02-08 1 views
1

쿼리 세트를 반복하고 모든 항목에 대해 사전을 만든 다음 모든 사전을 목록에 추가하려고합니다. 사전이 있는지 확인한 후 값이 업데이트되는지 확인해야합니다. 내 문제는 금액 값으로 목록을 정렬하는 방법을 모른다는 것입니다.사전의 목록을 작성하고 값으로 사전을 정렬하는 올바른 방법

아마도 이것이 딕트를 만드는 가장 좋은 방법이 아닐 수도 있습니다. 여기

내 코드입니다 :

#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

처럼 사전을 통해 항상 루프는 어떤 걸이다 달성하려고? 또는'{ "name123": { "amount": 8}}' –

+1

의 목록을 원한다면 query_set 샘플을 제공하십시오. 문제가 더 잘 설명됩니다. –

+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

Upvoted하지만 왜'output = sorted (dict_.items(), key = lambda x : x [1] [ 'amount'])가 아닌지를 물어 보자. –

+1

제안 해 주셔서 감사합니다. :) @OrDuan – Jarvis

0

jus를 들었을 때 목록에 사전을 추가하는 이유는 무엇입니까? 하나의 값으로, 코드를 복잡하게 만들 수 있습니다. 이 시도하고 당신

# 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 
+0

그냥 내 질문을 단순화하려고. 두 값을가집니다. 금액과 다른 값. –

관련 문제