0

I need to be able to pull the value of the key 'irr' from this json address in python:

IRR = conparameters['components'][i]['envelope'][j]['irr']

Even if 'irr' is any oher case, like IRR, Irr... etc.

Is that easy?

Barmar
  • 741,623
  • 53
  • 500
  • 612
David Pesetsky
  • 254
  • 5
  • 13
  • You need to loop through all the keys of the dictionary until you find one that matches `irr` case-insensitively. – Barmar Apr 08 '20 at 21:18
  • The following provides an example of a case-insensitive dictionary class that could be used to perform this action. It should be possible to recursively apply this data structure if needed. https://stackoverflow.com/a/2082169/3658702 – Jacob Turpin Apr 08 '20 at 21:20
  • @JacobTurpin But if he's getting the data from JSON, is it possible to make `json.loads()` use that dictionary class instead of the standard one? – Barmar Apr 08 '20 at 21:21
  • 1
    @Barmar - why yes, yes it is `json.loads(data, object_pairs_hook=CaseInsensitiveDict)`... – zwer Apr 08 '20 at 21:25
  • @zwer Cool! Post that as an answer. – Barmar Apr 08 '20 at 21:27

1 Answers1

0

There's nothing built-in that does it, you have to search for a matching key.

See Get the first item from an iterable that matches a condition for how to write a first() function that finds the first element of an iterable that matches a condition. I'll use that in the solution below.

cur = conparameters['components'][i]['envelope'][j]
key = first(cur.keys(), lambda k: lower(k) == 'irr')
IRR = cur[key]
Barmar
  • 741,623
  • 53
  • 500
  • 612