Python: Average a list and append to dictionary
Question: I have a dictionary of names with a number (a score) assigned to them. The
file is laid out as so:

    
    
    Person A,7
    Peron B,6
    

If a name is repeated in the file e.g. Person B occurred on 3 lines with 3
different scores I want to calculate the mean average of these scores then
append this result to a dictionary in the form of a list. However, I keep
encountering an error when i try to sort the dictionary. Code below.

    
    
    else:
    for key in results:
        keyValue = results[key]
        if len(keyValue) > 1:
            # Line below this needs modification
            keyValue = list(sum(keyValue)/len(keyValue))
            newResults[key] = keyValue
            # Error in above code...
        else:
            newResults[key] = keyValue
    print(newResults)
    print(sorted(zip(newResults.values(), newResults.keys()), reverse=True))
    

Results is a dictionary of the people (the keys) and their scores (the values)
where the values are lists so that:

    
    
    results = {'Bob':[7],'Jane':[8,9]}
    


Answer: If you're using Python 3.x you can use its `statistics` library which contains
a function `mean`. Now assuming that your dict looks like: `results = {'Bob':
[7], 'Jane': [8, 9]}` you can create a `newResults` dict like this:

    
    
    from statistics import mean
    newResults = {key: mean(results[key]) for key in results}
    

This is called dict comprehension and as you can see it's kinda intuitive.
Starting with `{` you're telling that dict is going to be created. Then with
`key: value` you're defining its structure. Lastly, with `for` loop you
iterate over a collection that will be used for the dict creation. You can
achieve the same with:

    
    
    newResults = {}
    for key in results:
        newResults[key] = mean(results[key])
    

You want to sort the dict in the end. Unfortunately it's not possible. You can
either create an `OrderedDict`, which remembers the items insertion order or a
list which will contain sorted keys to your dict. The latter will look like:

    
    
    sortedKeys = sorted(newResults, key=lambda x: newResults[x])
    

