Appending to a Dictionary Value List in Loop

后端 未结 3 442
半阙折子戏
半阙折子戏 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条回答
  •  梦毁少年i
    2021-01-27 01:37

    The problem you encounter comes from the way you create Scores:

    Scores=dict.fromkeys(lines,[])
    

    When using dict.fromkeys, the same value is used for all keys of the dict. Here, the same, one and only empty list is the common value for all your keys. So, whichever key you access it through, you always update the same list.

    When doing Scores[a[1]]=[], you actually create a new, different empty list, that becomes the value for the key a[1] only, so the problem disappears.

    You could create the dict differently, using a dict comprehension:

    Scores = {key: [] for key in lines} # here, a new empty list is created for each key
    

    or use a collections.defaultdict

    from collections import defaultdict
    
    Scores =  defaultdict(list)
    

    which will automatically initialize Score['your_key'] to an empty list when needed.

提交回复
热议问题