Iterating a dictionary key value and averaging with known count

python dictionary count values per key
python count occurrences of value in dictionary
count same values in dictionary python
counting frequency in dictionary python
iterate over dictionary python
python iterate dictionary key, value
python count unique values in dictionary
count of keys in dict

As a beginner in python,Im still trying to grasp the concept of dictionary count/loops better. So i've created a sample data to get my question across clearly. Below i have an unordered list of dictionaries containing the revenue information of a few shops. My question is, how do i get the average revenue of each shop - based on the count of reported revenue, reported by these shops?

     #Given data 
     revenue_list_of_dictionaries:
     [{'shop_ID': 1,
       'revenue': 15000},
      {'shop_ID': 2,
       'revenue': 12000},
      {'shop_ID': 1,
       'revenue': 8500},
      {'shop_ID': 3,
       'revenue': 5000}
      {'shop_ID': 1,
       'revenue': 3500}]

     data = revenue_list_of_dictionaries

     result = {}

     # Executing code to find total revenue for each shop ID
     for revenue_list in data:
         shop_ID = revenue_list['shop_ID']
         revenue_per_month = revenue_list['revenue']
         if shop_ID not in result:
             result[shop_ID] = revenue_per_month
         else:
             result[shop_ID] += revenue_per_month

Running the code above will give me:

         {'1':27000,
          '2':12000,
          '3':5000}

Based on each shop reporting count:

         {'1':3,
          '2':1,
          '3':1}

How do i find the average of each revenue reported so that my output will return the following:

         {'1': 9000,
          '2': 12000,
          '3': 5000}

If the total revenue is called a and the count b and they both have the same keys (which they have to), you can use a dict comprehension to calculate the average revenue c:

c = {key: value/b[key] for key, value in a.items()}

Counting the Number of keywords in a dictionary in python, How do you count the number of items in a dictionary? How to Iterate Through a Dictionary in Python: The Basics. Dictionaries are an useful and widely used data structure in Python. As a Python coder, you’ll often be in situations where you’ll need to iterate through a dictionary in Python, while you perform some actions on its key-value pairs.


If you want to manipulate your current approach to work, then user8408080's approach will work just fine.

Otherwise, as mentioned in the comments by @Chris_Rands, you can collect the revenues with a collections.defaultdict(), storing them as lists, then calculate the mean at the end:

from collections import defaultdict
from statistics import mean

revenues = [
    {"shop_ID": 1, "revenue": 15000},
    {"shop_ID": 2, "revenue": 12000},
    {"shop_ID": 1, "revenue": 8500},
    {"shop_ID": 3, "revenue": 5000},
    {"shop_ID": 1, "revenue": 3500},
]

counts = defaultdict(list)
for revenue in revenues:
    counts[revenue['shop_ID']].append(revenue['revenue'])

print({k: mean(v) for k, v in counts.items()})
# {1: 9000, 2: 12000, 3: 5000}

You could also have a collections.defaultdict() of collections.Counter(), and store the revenues and counts simultaneously:

from collections import defaultdict
from collections import Counter

revenues = [
    {"shop_ID": 1, "revenue": 15000},
    {"shop_ID": 2, "revenue": 12000},
    {"shop_ID": 1, "revenue": 8500},
    {"shop_ID": 3, "revenue": 5000},
    {"shop_ID": 1, "revenue": 3500},
]

counts = defaultdict(Counter)
for revenue in revenues:
    shp, rev = revenue['shop_ID'], revenue['revenue']
    counts[shp]['revenue'] += rev
    counts[shp]['count'] += 1

print({k: v['revenue'] / v['count'] for k, v in counts.items()})
# {1: 9000.0, 2: 12000.0, 3: 5000.0}

Note: In the first example I used statistic.median() to calculate the mean. You can also use sum(v) / len(v) if you want to.

Which method in a dictionary object gives you a list of the values in , works, and is faster than building an iterator, d. In this post, we will discuss how to iterate over a dictionary in C#. 1. foreach loop We can loop through all KeyValuePair<K,V>> in the dictionary and print the corresponding Key and Value from each pair. [crayon-5ed501105c2db363924910/] We can also iterate over the collection of keys and fetch the value using the …


You can do it without python packages, as follows:

result = {}
CountList = []

for dic in revenue_list_of_dictionaries:
    result.setdefault(dic.values()[0], 0)
    result[dic.values()[0]] += dic.values()[1]
    CountList.append(dic.values()[0])

#returning an average of all shop_Id revenues
for k, value in result.items():
    result[k] = value/CountList.count(k)

print result
#{1: 9000, 2: 12000, 3: 5000}

Python - can a dict have a value that is a list?, Which method in a dictionary object gives you a list of the values in the dictionary? This dictionary has 4 key-value pairs. The first key-value pair is age:24. The second key-value pair is height:170cm. The third key-value pair is weight:170lbs The fouth key-value pair is gender:male However, we write code just to get the keys of this dictionary. So we create a for loop that goes through all of the keys of this dictionary, Gregory.


Python, How do you add a key value pair to a dictionary? Key : three , Value : 3. Key : four , Value : 4. Key : one , Value : 1 Key : two , Value : 2 Key : three , Value : 3 Key : four , Value : 4. Key : one , Value : 1 Key : two , Value : 2 Key : three , Value : 3 Key : four , Value : 4. As you can see that all keys and values are printed out.


Python, This problem can be solved using naive method of loop. In this we just iterate through each key in dictionary and when a match is found, the counter is increased  Our profilin gDictionary variable contains 11,998,949 Key-Value records. The three most popular way of iterating over Dictionary variables in your C# program are discussed below: Method 1 (for loop, not foreach iteration)


python iterate dictionary key value Code Example, Python | Count number of items in a dictionary value that is a list Dictionaries are written with curly brackets, and they have keys and values. It return a boolean whether the object is an instance of the given class or not. Python | Delete items from dictionary while iterating · Python - Sorted order Dictionary items pairing  Python | Increment value in dictionary Sometimes, while working with dictionaries, we can have a use-case in which we require to increment a particular key’s value in dictionary. It may seem a quite straight forward problem, but catch comes when the existence of a key is not known, hence becomes a 2 step process at times.