Appending to a Dictionary Value List in Loop

后端 未结 3 447
半阙折子戏
半阙折子戏 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
    慢半拍i (楼主)
    2021-01-27 01:29

    IIUC, your dictionary is mapping place to score. You can leverage a defaultdict to replace your fromkeys method:

    from collections import defaultdict
    
    # Initialize an empty dictionary as you've done with default list entries
    scores = defaultdict(list)
    
    # Using the with context manager allows for safe file handling
    with open("ResultsTest.txt", 'r') as f1:
        lines = f1.read().splitlines()
    
    # Points lookup as you've done before
    lookup = {1: 100, 2: 90, 3: 80}
    
    for l in lines:
        team, name, place = l.split('\t') # unpacking makes this way more readable
    
        score = lookup.get(int(place))
        scores[team].append(score)
    
    

提交回复
热议问题