0

I have a dictionary like:

{
  'cashflowStatements': [
    {
      'endDate': '2019',
      'totalCashFromOperatingActivities': -40743000,
      'capitalExpenditures': -46141000
    },
    {
      'totalCashflowsFromInvestingActivities': 148919000,
      'endDate': '2018',
      'capitalExpenditures': -53753000
    },
    {
      'totalCashflowsFromInvestingActivities': -45493000,
      'endDate': '2017',
    },
    {
      'totalCashflowsFromInvestingActivities': -19651000,
      'endDate': '2016',
      'capitalExpenditures': -26266000
    }
  ]
}

I want to add the values to a variable, if they are in the dictionary.

Currently I have this solution for that:

       for year in dict['cashflowStatements']:
            freeCashflow = 0
            if 'totalCashFromOperatingActivities' in year:
                freeCashflow += year['totalCashFromOperatingActivities']
            if 'capitalExpenditures' in year:
                freeCashflow += year['capitalExpenditures']

Is there a better way to do this, maybe with less lines of code?

2 Answers2

1

Maybe something like this:

for year in dict['cashflowStatements']:
    freeCashflow = year.get('totalCashFromOperatingActivities', 0) + year.get('capitalExpenditures', 0)
rajkris
  • 1,775
  • 1
  • 9
  • 16
  • If we want `freeCashflow` to be intialized with the data present in the last dict of list ONLY, then why to iterate the entire list ? We can simply get last dict from list and use that. – Tabaene Haque Aug 09 '20 at 08:41
  • Maybe the code is not complete. More logic to be added in the loop. It depends on the questioners requirement – rajkris Aug 09 '20 at 08:49
0

Pythonic would be to use list comprehension like this -

d = {
  'cashflowStatements': [
    {
      'endDate': '2019',
      'totalCashFromOperatingActivities': -40743000,
      'capitalExpenditures': -46141000
    },
    {
      'totalCashflowsFromInvestingActivities': 148919000,
      'endDate': '2018',
      'capitalExpenditures': -53753000
    },
    {
      'totalCashflowsFromInvestingActivities': -45493000,
      'endDate': '2017',
    },
    {
      'totalCashflowsFromInvestingActivities': -19651000,
      'endDate': '2016',
      'capitalExpenditures': -26266000
    }
  ]
}

print(sum([year.get('totalCashFromOperatingActivities', 0) + year.get('capitalExpenditures', 0) for year in d['cashflowStatements']]))

Output: -166903000

Also looking at the question it seems like we want freeCashflow to be initialized with the sum of data present in last dict of list ONLY, then use below code.

print(d["cashflowStatements"][-1].get('totalCashFromOperatingActivities', 0) + d["cashflowStatements"][-1].get('capitalExpenditures', 0))

Output: -26266000

Tabaene Haque
  • 576
  • 2
  • 10
  • 'freeCashflow' is reinitialized in each loop. So I think this won't behave the same way as in question – rajkris Aug 09 '20 at 08:34