2013-03-29 88 views
0

基本上我已经创建了一个函数,它接受在http://stardict.sourceforge.net/Dictionaries.php下载的列表:对于例如oldList = [{ '一个':2},{ 'V':2}]和newList = [{ '一个':4 },{ 'C':4},{ 'E':5}]。我的目标是检查oldList中的每个字典关键字,如果它具有与newList中相同的字典关键字,则更新字典,否则附加到oldList。 因此,在这种情况下,来自oldList的关键字'a'将更新为值4,同样因为来自newList的关键字b和e在oldList中不存在,所以将该字典附加到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

由于这是工作的代码,它可能是一个更适合:HTTP://代码审查.stackexchange.com/ – bernie

+1

你确定你不想仅仅使用'dict'而不是'list'单个元素'dict's吗? – Jared

+0

在这种情况下,该结构被固定为一个编号列表 – user1741339

回答

0

可以使用update()方法:

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 

输出:

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

不考虑订单 – user1741339

+0

这就是您在处理字典时得到的结果:它是无序的。查看collections.OrderedDict()如果订单是你想要的。 –