【问题标题】:How to make a nested dictionary from a nested list in python [duplicate]如何从python中的嵌套列表制作嵌套字典[重复]
【发布时间】:2020-05-17 16:06:07
【问题描述】:

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

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

我想要这本词典:

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

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

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

【问题讨论】:

  • 到目前为止你尝试过什么?我会使用字典理解
  • 欢迎来到 SO!如果您需要建议,请查看 tourHow to Ask。这不是一个坏问题,但如果您发布了您的最佳尝试,它会有所帮助。请参阅How do I ask and answer homework questions?(即使不是家庭作业,也适用一些相同的建议)
  • 第一个字母总是会成为字典中的键吗?
  • @Sanders,这个问题之前有人问过,已经有了答案。
  • @Sushanth 非常相似,但不是重复的,因为它没有“无导入”约束。 OP 的期望输出也是无效的。

标签: python list dictionary indexing nested


【解决方案1】:

试试:

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

【讨论】:

  • OP 正在寻找无需导入的解决方案
  • @wjandrea 错过了,谢谢!
【解决方案2】:

假设要转换为键的列表元素始终具有 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}}

【讨论】:

  • 你在这里写了很多item[0][0],这让人难以阅读。将它分配给一个变量会有所帮助:k = item[0][0],然后你可以做if k not in nested_dictionary ... 同样[item[0][1]] 也有点难以阅读,所以也许你可以像这样解压缩item[0]k, k1 = item[0] 然后做@987654329 @。如果您想最大限度地打开包装,请查看我的答案。
【解决方案3】:

这可能最好通过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]

【讨论】:

    【解决方案4】:

    使用嵌套解包和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)

    【讨论】:

    • 声明d_nested[n] = i 似乎也更新了字典d。这是如何运作的?我预计d_nested 不会影响d
    • @KurtKline 严格来说不是,但d_nestedd 内部,如果这就是你的意思。或者您可能错过了d.setdefault
    • 我看到了但不明白。所以d_nested = d.setdefault(c, {}) 似乎在d 中创建了对嵌套字典的引用。
    • @Kurt 是的,这令人困惑。如果d[c] 存在,则d.setdefault 返回该值。如果d[c] 不存在,d.setdefault 将值设置为空字典并返回。
    【解决方案5】:
    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)
    

    【讨论】:

      【解决方案6】:

      如果使用 Python >= 3.8(使用海象运算符)

      nested_list = [['X1',5],['X2',6],['Y1',5],['Y2',6]]
      
      output = {}
      for left, right in nested_list: 
          if (xy := left[0]) in output: 
              output[xy][left[1]] = right
          else: 
              output[xy] = {str(left[1]):right}
      
      print(output) # -> {'X': {'1': 5, '2': 6}, 'Y': {'1': 5, '2': 6}}
      

      如果使用

      nested_list = [['X1',5],['X2',6],['Y1',5],['Y2',6]]
      
      output = {}
      for left, right in nested_list: 
          if left[0] in output: 
              output[left[0]][left[1]] = right
          else: 
              output[left[0]] = {str(left[1]):right}
      
      print(output) # -> {'X': {'1': 5, '2': 6}, 'Y': {'1': 5, '2': 6}}
      

      【讨论】:

      • 这里不需要海象运算符,这会降低代码的可读性和向后兼容。只需使用正常分配:xy = left[0]; if xy in output ...
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-21
      • 1970-01-01
      • 2020-12-21
      • 1970-01-01
      • 1970-01-01
      • 2021-05-10
      • 2023-03-11
      相关资源
      最近更新 更多