0

Basically I have created a function which takes in a list of dicts: for e.g oldList = [{'a':2}, {'v':2}] and newList = [{'a':4},{'c':4},{'e':5}]. My aim is to check for each dictionary key in the oldList and if it has the same dictionary key as in the newList update the dictionary, else append to the oldList. So in this case the key 'a' from oldList will get updated with the value 4, also since the keys b and e from the newList don't exist in the oldList append the dictionary to the oldList. Therefore you get [{'a': 4}, {'v': 2}, {'b': 4}, {'e': 5}]. I just want to know if there a better way to do this?

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}]
4

1 回答 1

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}
于 2013-03-29T22:01:23.460 回答