Python Forum
Help to flatten list of nested dictionaries
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help to flatten list of nested dictionaries
#3
I'm new to this forum and I don't know how to insert those nice code snippet boxes, but here is what I tried. It works to flatten the dictionaries, but only if there are no [ and ] brackets around the nested dictionaries, which is the way the API data is retrieved.

d = {'mid': {'h': '1.31', 'o': '1.32', 'c': '1.33', 'l': '1.34'}, 'volume': 99, 'time': '2019-02-22T21', 'complete': False}
def flatten(d):
    def items():
          for key, value in d.items():
               if isinstance(value, dict):
                    for subkey, subvalue in flatten(value).items():
                         yield key + "." + subkey, subvalue
               else:
                    yield key, value
    return dict(items())
dictout = flatten(d)
hi = dictout.get('mid.h')
lo = dictout.get('mid.l')
print("Hi= ",hi," and Lo= ",lo)
So like I say, this works fine on the dictionary line at the top, but the actual API line is a List with opening and closing []. I don't know how to get around that. Suggestions?
Reply


Messages In This Thread
RE: Help to flatten list of nested dictionaries - by shawbapmp - Feb-25-2019, 05:31 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Sort a list of dictionaries by the only dictionary key Calab 2 687 Apr-29-2024, 04:38 PM
Last Post: Calab
  Access list of dictionaries britesc 4 1,162 Jul-26-2023, 05:00 AM
Last Post: Pedroski55
  List all possibilities of a nested-list by flattened lists sparkt 1 975 Feb-23-2023, 02:21 PM
Last Post: sparkt
  Updating nested dict list keys tbaror 2 1,320 Feb-09-2022, 09:37 AM
Last Post: tbaror
  Python Program to Find the Total Sum of a Nested List vlearner 8 5,106 Jan-23-2022, 07:20 PM
Last Post: menator01
  Looping through nested elements and updating the original list Alex_James 3 2,201 Aug-19-2021, 12:05 PM
Last Post: Alex_James
  function that returns a list of dictionaries nostradamus64 2 1,825 May-06-2021, 09:58 PM
Last Post: nostradamus64
  convert List with dictionaries to a single dictionary iamaghost 3 2,915 Jan-22-2021, 03:56 PM
Last Post: iamaghost
  shuffle a nested list giorgosmarga 11 12,095 Nov-12-2020, 07:04 PM
Last Post: perfringo
Question Save list with nested list into CSV SpongeB0B 1 5,496 Oct-12-2020, 07:26 AM
Last Post: bowlofred

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020