Python Forum
From flat to nested structure
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
From flat to nested structure
#6
That looks super wacky, but sure whatever lol.

I guess a list of dicts, which represents the different sequences of characters might work. As you go through the data, you only ever modify the newest sequence (index -1 is the last index). Then, once a key is found that already exists in that dict, you start a new sequence.

Something like this?
>>> data = '''a : one
...  b : two
...  c : three
...  d : four
...  a : five
...  b : six
...  c : seven
...  d : eight
...  e : nine'''.split('\n')
>>> data
['a : one', ' b : two', ' c : three', ' d : four', ' a : five', ' b : six', ' c : seven', ' d : eight', ' e : nine']
>>> sequences = [{}]
>>> for item in data:
...   pair = item.split(':')
...   key = pair[0].strip()
...   value = pair[1].strip()
...
>>> for item in data:
...   pair = item.split(':')
...   key = pair[0].strip()
...   value = pair[1].strip()
...   if key in sequences[-1]:
...     # this key has already been seen, so we're starting a new sequence
...     sequences.append({})
...   sequences[-1][key] = value
...
>>> sequences
[{'d': 'four', 'b': 'two', 'a': 'one', 'c': 'three'}, {'d': 'eight', 'b': 'six', 'e': 'nine', 'a': 'five', 'c': 'seven'}]
>>> import pprint
>>> pprint.pprint(sequences)
[{'a': 'one', 'b': 'two', 'c': 'three', 'd': 'four'},
 {'a': 'five', 'b': 'six', 'c': 'seven', 'd': 'eight', 'e': 'nine'}]
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,975 Jul-20-2020, 07:18 PM
Last Post: princetonits
  Nested Data structure question arjunfen 7 4,310 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