基本上我已經創建了一個函數,它接受在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}]
由於這是工作的代碼,它可能是一個更適合:HTTP://代碼審查.stackexchange.com/ – bernie
你確定你不想僅僅使用'dict'而不是'list'單個元素'dict's嗎? – Jared
在這種情況下,該結構被固定爲一個編號列表 – user1741339