I need to answer the question how many kilos of cucumbers were sold. I am not interested in how many kilos were sold in a specific day, but i will be very happy if you show me formula how to get it. Also i want to know how to print only the previous part of dictionary(without weekday). It is my answer so far, can sb help me with that?
# listing = [
# { 'mass' : 20, 'name' : 'onion', 'weekday' : 'monday'},
# { 'mass' : 10, 'name' : 'garlic', 'weekday' : 'tuesday'},
# { 'mass' : 40, 'name' : 'carrot', 'weekday' : 'monday'},
# { 'mass' : 90, 'name' : 'cucumber', 'weekday' : 'saturday'},
# { 'mass' : 80, 'name' : 'onion', 'weekday' : 'sunday'},
# { 'mass' : 30, 'name' : 'parslay', 'weekday' : 'sunday'},
# { 'mass' : 20, 'name' : 'onion', 'weekday' : 'sunday'},
# { 'mass' : 10, 'name' : 'cucumber', 'weekday' : 'wednesday'},
# { 'mass' : 1, 'name' : 'garlic', 'weekday' : 'sunday'},
# ]
def list(listing):
for i in listing:
print(next(item for item in listing if item["name"] == "cucumber"))
print(list([{ 'mass' : 20, 'name' : 'onion', 'weekday' : 'monday'},{ 'mass' : 10, 'name' : 'garlic', 'weekday' : 'tuesday'},{ 'mass' : 40, 'name' : 'carrot', 'weekday' : 'monday'},{ 'mass' : 90, 'name' : 'cucumber', 'weekday' : 'saturday'},{ 'mass' : 80, 'name' : 'onion', 'weekday' : 'sunday'},{ 'mass' : 30, 'name' : 'parslay', 'weekday' : 'sunday'},{ 'mass' : 20, 'name' : 'onion', 'weekday' : 'sunday'},{ 'mass' : 10, 'name' : 'cucumber', 'weekday' : 'wednesday'},{ 'mass' : 1, 'name' : 'garlic', 'weekday' : 'sunday'}]))
CodePudding user response:
Use sum
with an appropriate conditional generator expression:
def cucu_mass(dcts):
return sum(dct["mass"] for dct in dcts if dct["name"] == "cucumber")
Some documentation:
CodePudding user response:
You can use a small comprehension with a condition:
sum(i['mass'] for i in listing if i['name'] == 'cucumber')
output: 100
You can add other conditions, here the days need to be on the weekend:
sum(i['mass'] for i in listing
if i['name'] == 'cucumber' and i['weekday'] in ('saturday', 'sunday'))
output: 90