如何在python中从不同长度的列表创建字典

ycl3bljg  于 2021-09-08  发布在  Java
关注(0)|答案(2)|浏览(337)

我有一个x列表,如下所示:

x =[[[1, 2]], [[2, 1], [2, 3]], [[3, 2]], [[4, 7, 6, 5]]]

我尝试在最终结果中创建一个字典列表,如下所示:

dict_list = [{"user_idx": 1, "partner_1": 2}, {"user_idx": 2, "partner_1": 1, "partner_2": 3}, 
            {"user_idx": 3, "partner_1": 2}, {"user_idx": 4, "partner_1":7, "partner_2": 6,"partner_3":5}]

如何使用python代码完成它?

pu3pd22g

pu3pd22g1#

尝试:

x =[[[1, 2]], [[2, 1], [2, 3]], [[3, 2]], [[4, 7, 6, 5]]]

out = {}
for g in x:
    for subl in g:
        out.setdefault(subl[0], []).extend(subl[1:])

out = [
    {
        "user_idx": k,
      **{"partner_{}".format(idx): i for idx, i in enumerate(v, 1)},
    }
    for k, v in out.items()
]
print(out)

印刷品:

[
    {"user_idx": 1, "partner_1": 2},
    {"user_idx": 2, "partner_1": 1, "partner_2": 3},
    {"user_idx": 3, "partner_1": 2},
    {"user_idx": 4, "partner_1": 7, "partner_2": 6, "partner_3": 5},
]
daupos2t

daupos2t2#

这显然需要一个单一的列表理解解决方案,尽管不可否认这有点失控:

dict_list = [
    {"user_idx": (s := list(chain.from_iterable(z if i == 0 else z[1:] 
                                   for i, z in enumerate(el))))[0],
   **{f"partner_{ii + 1}": p for ii, p in enumerate(s[1:])}}
     for el in x]
print(dict_list)

# Out:

[{'user_idx': 1, 'partner_1': 2}, 
 {'user_idx': 2, 'partner_1': 1, 'partner_2': 3}, 
 {'user_idx': 3, 'partner_1': 2}, 
 {'user_idx': 4, 'partner_1': 7, 'partner_2': 6, 'partner_3': 5}]

相关问题