As a challenge to myself, I wrote a solution to this Stack Overflow question. For completeness, the bulk of the question is as follows:
Problem
Input:
[
['key1', 'value1'],
['key2',
[
['key3', 'value3'],
['key4',
[
...
]
],
['key5', 'value5']
]
],
['key6', 'value6'],
]
Ouput:
{
"key1": "value1",
"key2": {
"key3": "value3",
"key4": ...,
"key5": "value5"
},
"key6": "value6"
}
Solution
Please note that this is my first attempt.
import pprint
def main():
lt = [ \
['key1', 'value1'], \
['key2', \
[ \
['key3', 'value3'], \
['key4', \
['key7','value7'] \
], \
['key5', 'value5'] \
] \
], \
['key6', 'value6'] \
]
print('Input:')
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(lt)
dt = lists2dict(lt, pp)
print('-' * 80)
print('Output:')
pp.pprint(dt)
def lists2dict(lt, pp):
# form a dict from a list of lists,
# if a key's value is a single-element list, just add the element
dt = {l[0]: l[1:] if len(l[1:]) > 1 else l[1] for l in lt}
# print('-' * 70)
# pp.pprint(dt)
for k,v in dt.items(): # step through the dict, looking for places to recurse
# print('k=%r, v=%r' %(k,v))
if isinstance(v, list): # a value which is a list needs to be converted to a dict
if isinstance(v[1], list): # only recurse if a to-be-parsed value has a list
dt[k] = lists2dict(v, pp)
else: # just a single k/v pair to parse
dt[k] = {v[0]: v[1]}
return dt
if __name__ == '__main__':
main()
If anyone has improvements, or a more efficient and/or Pythonic implementation, please share it.
\
you are using when defining the input are useless. Also you should never us\
to continue a line since you can wrap whatever expression you are writing in parenthesis(
and)
. \$\endgroup\$(
,[
, and{
) begin implicit line continuation. There is no need to use `` to continue a line so long as it's enclosed in a pair of matching brackets. \$\endgroup\$