Created On: October 06, 2022, Last Updated On: October 06, 2022

Python solutions

Public

By Ozzie Ghani3 new





from collections import defaultdict
import json

l = [( "tx", 'houston', 'richmond'),
("tx", 'dallas', 'lakewood'),
( "tx", 'houston', 'kessler'),
( "tx", 'dallas', 'cedars'),
( "ct", 'hartford', 'wethersfield'),
( "ct", 'hartford', 'parkville'),
( "ct", 'new haven', 'westville'),
( "fl", 'miami', 'gladview'),
("fl", 'orlando', 'parramore'),
( "fl", 'orlando', 'golden heights'),
( "fl", 'miami', 'el portal')]



def nested_dict(l):
    d = defaultdict(lambda:defaultdict(list))
    for x,y,z in l:
        d[x][y].append(z)
    return d


result = nested_dict(l)
print(json.dumps(result, indent=2))



#### Result
{
  "tx": {
    "houston": [
      "richmond",
      "kessler"
    ],
    "dallas": [
      "lakewood",
      "cedars"
    ]
  },
  "ct": {
    "hartford": [
      "wethersfield",
      "parkville"
    ],
    "new haven": [
      "westville"
    ]
  },
  "fl": {
    "miami": [
      "gladview",
      "el portal"
    ],
    "orlando": [
      "parramore",
      "golden heights"
    ]
  }
}