Create a list of dict python

1

I have the following function in python

def playersID(self, listDetals):
        listPlayersID = []
        tempDict = {}
        for x in listDetals:
            for y in x['result']['players']:
                tempDict.clear()
                tempDict['match_id'] = x['result']['match_id']
                tempDict.update(y)
                listPlayersID.append(tempDict)
        return listPlayersID

The parameter "listDetals" is a list of Dict and the function return is also a list of Dictionaries with a piece of listDetals in each position. The problem is in the "append" command.

Every time it is called, it fills ALL the list again, instead of just creating a new position at the end of it. Anyone have any idea why this?

    
asked by anonymous 05.09.2015 / 02:04

1 answer

0

When you use tempDict.clear() it affects the variable that has already been placed in the list, just change to tempDict = {} .

def playersID(self, listDetals):
    listPlayersID = []
    for x in listDetals:
        for y in x['result']['players']:
            tempDict = {'match_id': x['result']['match_id']}        
            tempDict.update(y)
            listPlayersID.append(tempDict)
    return listPlayersID

Detail, append() will always add to the end of the list, it will never replace the entire list with the new element. Review your code, preferably use unittest .

    
05.09.2015 / 03:48