ilyesBourouba
ilyesBourouba

Reputation: 101

python convert list with sub lists to dictionary

Hello i'm new to python.

i'm working with lists in python and i want to Convert a list named graph to dictionnary graph in PYTHON.

my have list :

graph = [
    ['01 Mai', 
      [
        ['Musset', 5],
        ['Place 11 Decembre 1960', 4],
        ["Sidi M'hamed", 3],
        ['El Hamma (haut)', 6]
      ]
    ], 
    ['Musset',
      [
        ['Place 11 Decembre 1960', 4],
        ["Sidi M'hamed", 3],
        ['El Hamma (haut)', 6], 
        ["Jardin d'Essai (haut)", 10]
      ],
    ]
]

i want the list to be a dictionary like that :

graph = {
  '01 mai':{
      'Musset':5, 
      'Place 11 Decembre 1960':4,
      "Sidi M'hamed":3,
      "El Hamma (haut)":6,
      },
  'Musset':{
    'Place 11 Decembre 1960':4,
    "Sidi M'hamed":3,
    "El Hamma (haut)":6,
    "Jardin d'Essai (haut)": 10,
    }
}

Upvotes: 0

Views: 140

Answers (3)

Ajax1234
Ajax1234

Reputation: 71451

You can use recursion to handle input of unknown depth:

graph = [['01 Mai', [['Musset', 5], ['Place 11 Decembre 1960', 4], ["Sidi M'hamed", 3], ['El Hamma (haut)', 6]]], ['Musset', [['Place 11 Decembre 1960', 4], ["Sidi M'hamed", 3], ['El Hamma (haut)', 6], ["Jardin d'Essai (haut)", 10]]]]
def to_dict(d):
  return {a:b if not isinstance(b, list) else to_dict(b) for a, b in d}

print(to_dict(graph))

Output:

{'01 Mai': {'Musset': 5, 'Place 11 Decembre 1960': 4, "Sidi M'hamed": 3, 'El Hamma (haut)': 6}, 'Musset': {'Place 11 Decembre 1960': 4, "Sidi M'hamed": 3, 'El Hamma (haut)': 6, "Jardin d'Essai (haut)": 10}}

Upvotes: 1

Amir Afianian
Amir Afianian

Reputation: 2795

An easy solution would be:

for item in graph:
    d[item[0]] = {record[0]: record[1] for record in item[1]}

Upvotes: 0

Netwave
Netwave

Reputation: 42678

A simple dict comprehension would do:

as_dict = {k: dict(v) for k,v in graph}

Playground

Upvotes: 5

Related Questions