Python Forum
From flat to nested structure
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
From flat to nested structure
#1
Most Venerable Coders,

I've got seemingly innocent problem I cannot crack properly (I'm not proficient in Python though). I've got a flat data structure in the form of (kind of) key-value pairing:

[inline]a : one
b : two
c : three
d : four
a : five
b : six
c : seven
d : eight
e : nine[/inline]

So, it's recurring group of the same keys associated with different values (number of key-values pairs can differ per one record though). I'm trying to build a corresponding dictionary out of it. I presume it has to be some kind of nested dictionary in the form:

[inline]{ 'OUTER KEY 1': {'a':'one', 'b':'two', 'c':'three', 'd':'four'},
'OUTER KEY 2': {'a':'five', 'b':'six', 'c':'seven', 'd':'eight', 'e':'nine'},
...
}[/inline]

Where outer keys can be just values of incremental counter. I imagine logic for looping the original structure would be something like:

[inline]If item == 'a':
Create outer key
Populate inner value with keys and values until next 'a'[/inline]

I was able to process the text file and extract the key-value pairs in the form of list or tuple but cannot properly build a dictionary out of it. For example, I've got list of tuples like that:

[('a', 'one'), ('b', 'two'), ('c', 'three'), ('d', 'four')]

Associating keys with values using zip won't help as keys repeat themselves. I've tried defaultdict and grouping around keys but that gives all values associated with one key - clever but not exactly what I need. Does anyone could point me to a right direction?
Reply


Messages In This Thread
From flat to nested structure - by CptHaddock - Mar-19-2018, 08:20 PM
RE: From flat to nested structure - by nilamo - Mar-19-2018, 08:46 PM
RE: From flat to nested structure - by CptHaddock - Mar-19-2018, 09:33 PM
RE: From flat to nested structure - by nilamo - Mar-20-2018, 03:57 PM
RE: From flat to nested structure - by CptHaddock - Mar-21-2018, 07:31 PM
RE: From flat to nested structure - by nilamo - Mar-21-2018, 07:50 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  I’m Flat out struggling to understand list indexes gr3yali3n 7 2,945 Jul-20-2020, 07:18 PM
Last Post: princetonits
  Nested Data structure question arjunfen 7 4,289 Feb-22-2019, 02:18 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

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