Create a list of python Dict

Asked

Viewed 886 times

1

I have the following python function

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 "listDetals" parameter is a list of Dict and the return of the function is also a list of Dicionario with a piece of listDetals at each position. The problem is in the command "append".

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

  • Try to change tempDict.clear() for tempDict = {} and see if it works.

1 answer

1


When you use tempDict.clear() it affects the variable that has also 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, will never replace the entire list with the new element. Review your code, preferably use unittest.

  • 1

    Thank you very much! I changed the tempDict.clear() to tempDict = {} and solved!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.