Python Forum
From flat to nested structure
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
From flat to nested structure
#2
What about a dict, with the value being a list of every occurrence?

>>> 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']
>>> parsed = {}
>>> for item in data:
...   key, value = item.split(':')
...   key = key.strip()
...   value = value.strip()
...   if key not in parsed:
...     parsed[key] = []
...   parsed[key].append(value)
...
>>> parsed
{'c': ['three', 'seven'], 'd': ['four', 'eight'], 'b': ['two', 'six'], 'a': ['one', 'five'], '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 3,032 Jul-20-2020, 07:18 PM
Last Post: princetonits
  Nested Data structure question arjunfen 7 4,405 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