Appending to a Dictionary Value List in Loop

后端 未结 3 445
半阙折子戏
半阙折子戏 2021-01-27 01:23

I have some code where I am using a list of names, and a file (eventually multiple files) of results (team, name, place). The end result I am looking for is to have each person

3条回答
  •  星月不相逢
    2021-01-27 01:40

    By using Scores=dict.fromkeys(lines,[]) you're initializing every key of the dict with a reference to the same list, so changes made to the list are reflected across all keys. You can use a dict comprehension for initialization instead:

    Scores = {line: [] for line in lines}
    

    Alternatively, you can initialize Scores as a normal dict {} and use the dict.setdefault method to initialize its keys with lists:

    Scores.setdefault(a[1], []).append(score)
    

提交回复
热议问题