2013-03-29 3 views
0

기본적으로 나는 oldList = [{ 'a': 2}, { 'v': 2}] 및 newList = [{ 'a': 4에 대한 dicts의 목록을 취하는 함수를 만들었습니다. }, { 'c': 4}, { 'e': 5}]. 내 목표는 oldList의 각 사전 키를 확인하고 newList와 동일한 사전 키가 있으면 사전을 업데이트하고 그렇지 않으면 oldList에 추가하는 것입니다. 그래서이 경우 newList의 키 b와 e가 oldList에 없기 때문에 oldList의 키 'a'는 값 4로 업데이트됩니다 oldList에 사전을 추가하십시오. 그러므로 당신은 {{ 'a': 4}, { 'v': 2}, { 'b': 4}, { 'e': 5}]를 얻습니다. 이 작업을 수행 할 수있는 더 좋은 방법이 있는지 알고 싶습니다.사전 정렬

def sortList(oldList, newList): 
    for new in newList: #{'a':4},{'c':4},{'e':5} 
     isAdd = True 
     for old in oldList:#{'a':2}, {'v':2}    
      if new.keys()[0] == old.keys()[0]: #a == a 
       isAdd = False 
       old.update(new) # update dict 
     if isAdd: 
      oldList.append(new) #if value not in oldList append to it 
    return oldList 

sortedDict = sortList([{'a':2}, {'v':2}],[{'a':4},{'b':4},{'e':5}]) 
print sortedDict 

[{'a': 4}, {'v': 2}, {'b': 4}, {'e': 5}] 
+1

코드를 작동하고, 그것은 더 나은 적합을 할 수있다 // 코드 검토를 .stackexchange.com/ – bernie

+1

단일 요소'dict'의'list'보다는'dict'을 사용하고 싶지 않습니까? – Jared

+0

구조는이 경우 dicts 목록으로 수정됩니다. – user1741339

답변

0

업데이트() 메소드를 사용할 수 있습니다

oldList = dict(a=2,v=2) 
newList = dict(a=4,c=4,e=5) 
oldList.update(newList)  # Update the old list with new items in the new one 
print oldList 

출력은 : HTTP :이 이후

{'a': 4, 'c': 4, 'e': 5, 'v': 2} 
+0

계정으로 주문하지 않습니다. – user1741339

+0

그게 바로 dict을 다룰 때 얻는 것입니다. 순서는 정해져 있지 않습니다. collections.OrderedDict()를 살펴보십시오. 주문이 원하는 경우. –