Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In python one list converted to dict like a tree topology

In python2.7, I have one list

['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q']

and I need to transform into a dict like

{
'A':['B','C'],
'B':['D','E'],
'C':['F','G'],
'D':['H','I'],
'E':['J','K'],
'F':['L','M'],
'G':['N','O'],
'H':['P','Q'],
'I':[],
'J':[],
'K':[],
'L':[],
'M':[],
'N':[],
'O':[],
'P':[],
'Q':[]
}
like image 316
Arthas Avatar asked Jan 01 '23 02:01

Arthas


1 Answers

With zip() and itertools.izip_longest() you can do that like:

Code:

import itertools as it

in_data = list('ABCDEFGHIJKLMNOPQ')
out_data = {k: list(v) if v else [] for k, v in
            it.izip_longest(in_data, zip(in_data[1::2], in_data[2::2]))}

import json
print(json.dumps(out_data, indent=2))

Results:

{
  "A": [
    "B", 
    "C"
  ], 
  "C": [
    "F", 
    "G"
  ], 
  "B": [
    "D", 
    "E"
  ], 
  "E": [
    "J", 
    "K"
  ], 
  "D": [
    "H", 
    "I"
  ], 
  "G": [
    "N", 
    "O"
  ], 
  "F": [
    "L", 
    "M"
  ], 
  "I": [], 
  "H": [
    "P", 
    "Q"
  ], 
  "K": [], 
  "J": [], 
  "M": [], 
  "L": [], 
  "O": [], 
  "N": [], 
  "Q": [], 
  "P": []
}
like image 111
Stephen Rauch Avatar answered Jan 13 '23 15:01

Stephen Rauch