Python Workout 03 - Dictionary Calculations

Overall difficulty:

Objective: This workout provides practice with accessing dictionaries and performing calculations.

Problem: Create a function that takes a list of dictionaries and returns the sum of people’s budgets

Examples:

get_budgets([
  { "name": "John", "age": 28, "budget": 23000 },
  { "name": "Steve",  "age": 32, "budget": 40000 },
  { "name": "Martin",  "age": 16, "budget": 2700 }
]) ➞ 65700

get_budgets([
  { "name": "John",  "age": 21, "budget": 29000 },
  { "name": "Steve",  "age": 32, "budget": 32000 },
  { "name": "Martin",  "age": 16, "budget": 1600 }
]) ➞ 62600 

Submission

SImply post your code and a screenshot of your results.

Please format your Python code and blur it or place it in a hidden section.

This workout will be released on Monday April 3, 2023, and the author’s solution will be posted on Sunday April 9, 2023.

1 Like
1 Like
info = [
  { "name": "John", "age": 28, "budget": 23000 },
  { "name": "Steve",  "age": 32, "budget": 40000 },
  { "name": "Martin",  "age": 16, "budget": 2700 }
]


def get_budgets(value: list) -> float:
  """
    Takes a list of Dictionary of Employees 
    and returns the SUM of their budget
  """
  return sum([item['budget'] for item in value])


print(get_budgets(info))
1 Like

Hi ,

My submission for the workout:

image

def fun(array_dict):
  sum=0
  for l in (array_dict):
      sum+=(l["budget"])
  print(f'Total Budget is ${sum}')
1 Like

Great job @AntrikshSharma, @JordanSchnurman, and @Anurag

def get_budgets(budget):
total_budget = 0
for b in budget:
total_budget += b[“budget”]
return total_budget

budget = [
{ “name”: “John”, “age”: 21, “budget”: 29000 },
{ “name”: “Steve”, “age”: 32, “budget”: 32000 },
{ “name”: “Martin”, “age”: 16, “budget”: 1600 }
]

get_budgets(budget)
w03_python

Here is my solution

budget = [
{ “name”: “John”, “age”: 21, “budget”: 29000 },
{ “name”: “Steve”, “age”: 32, “budget”: 32000 },
{ “name”: “Martin”, “age”: 16, “budget”: 1600 }
]

def get_budgets(listDict):
    sum = 0
    for amount in listDict:
        for k,v in amount.items():
            if k == 'budget':
                sum = sum + v
    return sum
2 Likes

Love the participation on this. Well done everyone

1 Like

I’m not a fan of loops when they aren’t necessary, so I used map() instead.

def get_budgets(lst):
  return sum(map(lambda d: d["budget"], lst))

More verbosely:

def get_budgets(list_dict):
  extract_budgets = map(lambda dct: dct["budget"], list_dict)
  sum_budgets = sum(extract_budgets)
  return sum_budgets