在python中将嵌套列表转换为字典

dgenwo3n  于 2023-01-18  发布在  Python
关注(0)|答案(4)|浏览(158)

我需要将嵌套列表result = [[450, 455, 458], [452, 454, 456, 457], [451, 453]]转换为字典,如下所示:

{
    0: 
         {
             450: None,
             455: 450,
             458: 450
         },
    1:   {
             452: None,
             454: 452,
             456: 452,
             457: 452
         },
    2:   {
             451: None,
             453: 451
         }

}

请看一下并协助:

result_group = {}
for sub_group in result:
    group_count = 0
    first_rel_item = 0
    result_group[group_count] = dict()
    for item in sub_group:
        if item == sub_group[0]:
            result_group[group_count][item] = None
            first_rel_item = item
            continue
        result_group[group_count]['item'] = first_rel_face
        group_count += 1

我搞砸了这一点,因为我得到关键错误:1不能添加到字典。

sqxo8psd

sqxo8psd1#

这是一种方法:

lst = [[450, 455, 458], [452, 454, 457], [451, 453]]

res = {i: {w: None if w == v[0] else v[0] for w in v}
          for i, v in enumerate(lst)}
    • 结果**
{0: {450: None, 455: 450, 458: 450},
 1: {452: None, 454: 452, 457: 452},
 2: {451: None, 453: 451}}
    • 说明**
  • 使用三进制语句确定选择None还是v[0]
  • 使用enumerate提取嵌套列表的索引。
mu0hgdu0

mu0hgdu02#

试试这个:

result_group = {}
group_count = 0
for sub_group in result:
    first_rel_item = 0
    result_group[group_count] = {}
    result_group[group_count][sub_group[0]] = None
    previtem = sub_group[0]
    for item in sub_group[1:]:
        result_group[group_count][item] = previtem
        previtem = item
    group_count += 1
v440hwme

v440hwme3#

你可以在这里使用列表解析:

>>> result = [[450, 455, 458], [452, 454, 457], [451, 453]]

>>> dict(enumerate({**{i: a[0] for i in a[1:]}, **{a[0]: None}}
                   for a in result))

{0: {450: None, 455: 450, 458: 450},
 1: {452: None, 454: 452, 457: 452},
 2: {451: None, 453: 451}}

注意:这里使用了“扩展的”可迭代解包,这是在Python 3.5中引入的。z = {**x, **y}合并了字典xy
每个a都是result的子列表。您希望使用a[0]作为第1个元素及以上元素的值,并使用None作为第0个元素。
这里的假设是,您只希望子列表的第0个元素具有相应的None值(如果第0个元素在某处重复出现,它将使用第0个元素作为它的值,如@jpp的答案所示)。

bt1cpqcv

bt1cpqcv4#

# the nice solutions were already given, so by foot:

d = {}
result = [[450, 455, 458], [452, 454, 457], [451, 453]]

for idx,l in enumerate(result): # returns the index and the sublists data
    rMin = min(l)
    d[idx] = {}  # create a inner dict at key idx
    for i in l:
        d[idx][i] = None if i == rMin else rMin   # fill inner dicts keys

print(d)

输出:

{0: {450: None, 455: 450, 458: 450},
 1: {452: None, 454: 452, 457: 452},
 2: {451: None, 453: 451}}

相关问题