Mar-19-2018, 08:20 PM
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:
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?
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?