为了账号安全,请及时绑定邮箱和手机立即绑定

如何从python中的嵌套列表制作嵌套字典

如何从python中的嵌套列表制作嵌套字典

开心每一天1111 2022-11-24 14:56:23
基本上我有一个嵌套列表:nested_list = [['X1',5],['X2',6],['Y1',5],['Y2',6]]我想要这本字典:nested_dictionary = {'X': {'1':5, '2':6},'Y':{'1':5,'2':6}}有谁知道如何解决这个问题?有些人通过导入来做到这一点,但我正在寻找无需导入的解决方案
查看完整描述

5 回答

?
MM们

TA贡献1886条经验 获得超2个赞

尝试:


nested_list = [['X1', 5], ['X2', 6], ['Y1', 5], ['Y2', 6]]

nested_dict = {}

for sublist in nested_list:

    outer_key = sublist[0][0]

    inner_key = sublist[0][1]

    value = sublist[1]

    if outer_key in nested_dict:

        nested_dict[outer_key][inner_key] = value

    else:

        nested_dict[outer_key] = {inner_key: value}


print(nested_dict)

# output: {'X': {'1': 5, '2': 6}, 'Y': {'1': 5, '2': 6}}


查看完整回答
反对 回复 2022-11-24
?
回首忆惘然

TA贡献1847条经验 获得超11个赞

这可能最好通过 完成collections.defaultdict,但这需要导入。


不导入的另一种方法可能是:


nested_list = [['X1',5],['X2',6],['Y1',5],['Y2',6]]


final_dict = {}


for to_slice, value in nested_list:

    outer_key = to_slice[0]

    inner_key = to_slice[1:]


    if outer_key not in final_dict:

        final_dict[outer_key] = {}


    final_dict[outer_key][inner_key] = value


print(final_dict)

这假定外键始终是to_slice. 但是如果外键是 中的最后一个字符to_slice,那么您可能需要将代码中的相关行更改为:


outer_key = to_slice[:-1]

inner_key = to_slice[-1]


查看完整回答
反对 回复 2022-11-24
?
幕布斯7119047

TA贡献1794条经验 获得超8个赞

dict={}

key =[]

value = {}

for item in nested_list:

  for i in item[0]:

    if i.isalpha() and i not in key :

      key.append(i)

    if i.isnumeric():

     value[i]=item[1]


for k in key:

  dict[k]= value


print(dict)


查看完整回答
反对 回复 2022-11-24
?
繁星coding

TA贡献1797条经验 获得超4个赞

此代码假设要转换为键的列表元素始终具有 2 个字符。


nested_list = [['X1',5],['X2',6],['Y1',5],['Y2',6]]

nested_dictionary = {}

for item in nested_list:

  if not item[0][0] in nested_dictionary: # If the first letter isn't already in the dictionary

    nested_dictionary[item[0][0]] = {} # Add a blank nested dictionary

  nested_dictionary[item[0][0]][item[0][1]] = item[1] # Set the value

print(nested_dictionary)

输出:


{'X': {'1': 5, '2': 6}, 'Y': {'1': 5, '2': 6}}


查看完整回答
反对 回复 2022-11-24
?
翻阅古今

TA贡献1780条经验 获得超5个赞

使用嵌套解包 and dict.setdefault,您可以很容易地完成此操作:


d = {}

for (c, n), i in nested_list:

    d_nested = d.setdefault(c, {})

    d_nested[n] = i


print(d)  # -> {'X': {'1': 5, '2': 6}, 'Y': {'1': 5, '2': 6}}

nested_list[x][0]如果可以有两位数,拆包部分会稍微复杂一点:


for (c, *n), m in nested_list:

    n = ''.join(n)

    ...

FWIW,如果你被允许进口,我会用defaultdict(dict)


查看完整回答
反对 回复 2022-11-24
  • 5 回答
  • 0 关注
  • 90 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信