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

基本上我有一个嵌套列表:

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

我想要这本字典:

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

有谁知道如何解决这个问题?

有些人通过导入来做到这一点,但我正在寻找无需导入的解决方案


开心每一天1111
浏览 92回答 5
5回答

MM们

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

回首忆惘然

这可能最好通过 完成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] = valueprint(final_dict)这假定外键始终是to_slice. 但是如果外键是 中的最后一个字符to_slice,那么您可能需要将代码中的相关行更改为:outer_key = to_slice[:-1]inner_key = to_slice[-1]

幕布斯7119047

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]= valueprint(dict)

繁星coding

此代码假设要转换为键的列表元素始终具有 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 valueprint(nested_dictionary)输出:{'X': {'1': 5, '2': 6}, 'Y': {'1': 5, '2': 6}}

翻阅古今

使用嵌套解包 and dict.setdefault,您可以很容易地完成此操作:d = {}for (c, n), i in nested_list:    d_nested = d.setdefault(c, {})    d_nested[n] = iprint(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)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python