snippetpythonMinor
Recursively convert a list of lists into a dict of dicts
Viewed 0 times
dictdictsconvertintorecursivelylistslist
Problem
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:
Ouput:
Solution
Please note that this is my first attempt.
If anyone has improvements, or a more efficient and/or Pythonic implementation, please share it.
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.
Solution
You could simplify your function:
It seems to work.
def nested_pairs2dict(pairs):
d = {}
for k, v in pairs:
if isinstance(v, list): # assumes v is also list of pairs
v = nested_pairs2dict(v)
d[k] = v
return dIt seems to work.
Code Snippets
def nested_pairs2dict(pairs):
d = {}
for k, v in pairs:
if isinstance(v, list): # assumes v is also list of pairs
v = nested_pairs2dict(v)
d[k] = v
return dContext
StackExchange Code Review Q#38038, answer score: 6
Revisions (0)
No revisions yet.