Python Dictionary - find average of value from other values

守給你的承諾、 提交于 2019-12-09 23:48:47

问题


I have the following list

count = 3.5, price = 2500

count = 3, price = 400

count = 2, price = 3000

count = 3.5, price = 750

count = 2, price = 500

I want to find the average price for all where the count is the same. For example:

count = 2, price = 3000

count = 2, price = 500

3000 + 500 = 3500

3500/2 = 1750

Avg for 'count 2' is 1750

Here's my code so far

avg_list = [value["average"] for value in dictionary_database_list] 

counter_obj = collections.Counter(count_list)

print ("AVG:")

for i in counter_obj:

    print (i, counter_obj[i])

回答1:


I'll admit I'm not 100% clear on what you're looking for here, but I'll give it a shot:

A good strategy when you want to iterate over a list of "things" and accumulate some kind of information about "the same kind of thing" is to use a hash table. In Python, we usually use a dict for algorithms that require a hash table.

To collect enough information to get the average price for each item in your list, we need:

a) the total number of items with a specific "count"

b) the total price of items with a specific "count"

So let's build a data structure that maps a "count" to a dict containing "total items" and "total price" for the item with that "count".

Let's take our input in the format:

item_list = [
    {'count': 3.5, 'price': 2500},
    {'count': 3, 'price': 400},
    {'count': 2, 'price': 3000},
    {'count': 3.5, 'price': 750},
    {'count': 2, 'price': 500},
]

Now let's map the info about "total items" and "total price" in a dict called items_by_count:

for item in item_list:
    count, price = item['count'], item['price']
    items_by_count[count]['total_items'] += 1
    items_by_count[count]['total_price'] += price

But wait! items_by_count[count] will throw a KeyError if count isn't already in the dict. This is a good use case for defaultdict. Let's define the default value of a count we've never seen before as 0 total price, and 0 total items:

from collections import defaultdict
items_by_count = defaultdict(lambda: {
    'total_items': 0,
    'total_price': 0
})

Now our code won't throw an exception every time we see a new value for count.

Finally, we need to actually take the average. Let's get the information we need in another dict, mapping count to average price. This is a good use case for a dict comprehension:

{count: item['total_price'] / item['total_items']
for count, item in items_by_count.iteritems()}

This iterates over the items_by_count dict and creates the new dict that we want.

Putting it all together:

from collections import defaultdict

def get_average_price(item_list):
    items_by_count = defaultdict(lambda: {
        'total_items': 0,
        'total_price': 0
    })

    for item in item_list:
        count, price = item['count'], item['price']
        items_by_count[count]['total_items'] += 1
        items_by_count[count]['total_price'] += price

    return {count: item['total_price'] / item['total_items']
            for count, item in items_by_count.iteritems()}

If we pass in our example input dict, this function returns: {3.5: 1625, 2: 1750, 3: 400}

Which is hopefully the output you want! Be cautious of gotchas like float division in your particular Python version.




回答2:


You need to iterate over your items

See documentation

  • avg(dictionary.values()) is probably what you want


来源:https://stackoverflow.com/questions/42309909/python-dictionary-find-average-of-value-from-other-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!