2012-05-16 17 views
0

我有以下兩個Django的ValueQuerySets。如何使用另一個ValueQuerySet更新ValueQuerySet?

dict1 = [{'user': 1, 'total_bookmarked': 2}, {'user': 2, 'total_bookmarked': 3}] 

dict2 = [{'user': 1, 'name': 'Joe'}, {'user': 2, 'name': 'Paula'}] 

我如何合併兩個ValueQuerySet,這樣我可以得到如下:

dict3 = [{'user': 1, 'name': 'Joe', 'total_bookmarked':2}, {'user': 2, 'name': 'Paula', 'total_bookmarked': 3}] 

我將如何做到這一點?我曾經想過將這些轉換回Python列表的字典,但我不確定如何處理它,即使它工作。

+1

是否無法在一個查詢中獲得全部內容?這會更有效率。 – jdi

回答

0

如果他們只是無序列表或字典這將是

list1 = [{'user': 1, 'total_bookmarked': 2}, {'user': 2, 'total_bookmarked': 3}] 
list2 = [{'user': 1, 'name': 'Joe'}, {'user': 2, 'name': 'Paula'}] 
list3 = [] 
for d1 in list1: 
    for d2 in list2: 
     if d1['user'] == d2['user']: 
      d3 = dict(d1.items()+d2.items() 
      list3.append(d3) 
      break 
     else: 
      continue 

有一個更好的方法,如果你的列表是通過用戶

list1 = [{'user': 1, 'total_bookmarked': 2}, {'user': 2, 'total_bookmarked': 3}] 
list2 = [{'user': 1, 'name': 'Joe'}, {'user': 2, 'name': 'Paula'}] 

list3 = [dict(d1.items()+d2.items()) for (d1, d2) in zip(list1,list2)] 
2

我首先建議你試試,看有序如果你可以在一個查詢中得到它,因爲它更高效。但是,如果你想更新與第二列表第一列表,它們都以相同的順序:

list1 = [{'user': 1, 'total_bookmarked': 2}, {'user': 2, 'total_bookmarked': 3}] 
list2 = [{'user': 1, 'name': 'Joe'}, {'user': 2, 'name': 'Paula'}] 

for a,b in zip(list1, list2): 
    a.update(b) 

可以進一步提高效率,如果他們是非常大的列表使用izip

from itertools import izip 

for a,b in izip(list1, list2): 
    a.update(b) 

如果因爲某些原因,他們不都已經被用戶分類:

from operator import itemgetter 

list1.sort(key=itemgetter('user')) 
list2.sort(key=itemgetter('user')) 

我會避免爲解決方案使用嵌套for循環,因爲它不會那麼高效。

+0

值得指出的是,更新列表的列表在列表中1 –

+0

@PaulSeeb:我已經說過它會更新第一個列表和第二個列表。 – jdi

相關問題