Finding mean of a values in a dictionary without using .values() etc

前端 未结 10 1302
挽巷
挽巷 2021-01-02 17:29

I have a dictionary that looks like:

G={\'E\': 18.0, \'D\': 17.0, \'C\': 19.0, \'B\': 15.0, \'A\': 0}

I have to find the mean of the values

相关标签:
10条回答
  • 2021-01-02 17:55

    Use G.values() to get all the values from a dictionary.

    G = {'E': 18.0, 'D': 17.0, 'C': 19.0, 'B': 15.0, 'A': 0}
    d = float(sum(G.values())) / len(G)
    print (d)
    

    This prints 13.8.

    Note that there is a difference between Python 2 and Python 3 here. In Python 2, G.values() is a newly constructed list of values. In Python 3, it is a generator, which can be thought of as a “lazy list”. The same thing is called G.itervalues() in Python 2.

    0 讨论(0)
  • 2021-01-02 17:57

    You want:

    mean = sum([G[key] for key in G])/float(len(G))
    

    Your original code will also produce a:

    TypeError: 'int' object is not iterable
    

    when you try to sum the values.

    0 讨论(0)
  • 2021-01-02 17:59

    What I suggest instead of the current answers is adopting a functional programming paradigm that is reusable and flexible. For example, creating a function to calculate any statistic on list values contained within a simple dict:

    def summarize_dict(dictionary, function):
            dict_new = {}
        for k,v in dictionary.items():
            dict_new[k] = function(v)
        return dict_new
    

    Testing:

    import numpy as np
    
    keys = ["a","b","c","d","e"]
    values = [range(2),range(4),range(6),range(8),range(10)]
    dictionary = dict(zip(keys, values))
    
    summarize_dict(dictionary, np.mean)
    

    Yields:

    {'a': 0.5, 'b': 1.5, 'c': 2.5, 'd': 3.5, 'e': 4.5}
    
    0 讨论(0)
  • 2021-01-02 18:02

    Suppose you have a dictionary with multiple keys, each having a list of values:

    your_averaged_dictionary = {key: np.mean(values) for key, values in your_dictionary}
    
    0 讨论(0)
提交回复
热议问题