HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonMinor

Recursively convert a list of lists into a dict of dicts

Submitted by: @import:stackexchange-codereview··
0
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:

[
  ['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:

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 d


It 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 d

Context

StackExchange Code Review Q#38038, answer score: 6

Revisions (0)

No revisions yet.