简体   繁体   English

python 将带有子列表的列表转换为字典

[英]python convert list with sub lists to dictionary

Hello i'm new to python.您好,我是 python 的新用户。

i'm working with lists in python and i want to Convert a list named graph to dictionnary graph in PYTHON .我正在处理 python 中的列表,我想将名为graphlist转换为PYTHON中的dictionnary

my have list :我有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, } }

A simple dict comprehension would do:一个简单的字典理解会做:

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

Playground操场

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: 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}}

An easy solution would be:一个简单的解决方案是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM