I'm trying to randomize 5 items from a dict then sum up the value of the 5 items?
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))
CodePudding user response:
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))
CodePudding user response:
Random dicts
To get random dicts you can do it this way.
randomlist = random.sample(list(mydict.items()), 5)
dict(randomlist)
Result:
{10: {'name': 'item10', 'price': 14},
8: {'name': 'item8', 'price': 12},
7: {'name': 'item7', 'price': 11},
9: {'name': 'item9', 'price': 14},
5: {'name': 'item5', 'price': 13}}
Get final sum fast
But if you only look for final sum of prices you can do it a bit faster.
randomlist = random.sample(list(mydict.values()), 5)
sum(x['price'] for x in randomlist)
Result:
69.0
V3 the compact one
sum(random.sample([x['price'] for x in mydict.values()], 5))