Search code examples
pythondictionaryrandomaggregatesample

How do I aggregate 5 random samples of a dict?


I'm trying to sample 5 items from a dict then aggregate them by sum. In this case by building a sum of all 5 prices. How do I do that?

import random

mydict = {
    1: {"name":"item1","price": 16}, 
    2: {"name":"item2","price": 14},
    3: {"name":"item3","price": 16}, 
    4: {"name":"item4","price": 14}, 
    5: {"name":"item5","price": 13},
    6: {"name":"item6","price": 16},
    7: {"name":"item7","price": 11}, 
    8: {"name":"item8","price": 12}, 
    9: {"name":"item9","price": 14},
    10: {"name":"item10","price": 14},
}

randomlist = random.sample(mydict.items(), 5)
print(sum(randomlist)) # This line needs to work properly.

Solution

  • You don't care about the keys 1, 2, 3, just use mydict.values()

    Then take you have a list of 5 dict {name:,price:}, takes al the names, and all the prices for the sum

    randomlist = random.sample(list(mydict.values()), 5)
    print("Prices of", ",".join(item['name'] for item in randomlist))
    print(sum(item['price'] for item in randomlist))