简体   繁体   English

从列表列表生成嵌套字典

[英]Generating a nested dictionary from a list of lists

I am new to python and I'm trying to filter my data based on a list of lists with some common values.我是 python 的新手,我正在尝试根据具有一些常见值的列表列表过滤我的数据。 My input is a list of list.我的输入是列表列表。 I tried using numpy array with unique rows but I guess the logic would be the same.我尝试使用具有唯一行的 numpy 数组,但我想逻辑是相同的。

A = [['apple', 'green', 'sweet', 1.5], 
     ['apple', 'green', 'sweet', 1.0],
     ['apple', 'red', 'sweet', 2.0],
     ['orange', 'orange', 'sour', 1.0],
     ['orange', 'orange', 'sweet', 1.2],
     ['apple', 'yellow', 'sour', 0.5],
     ['banana', 'yellow', 'sweet', 1.0]]

I want an output that is something like:我想要一个 output 是这样的:

A_dict = {'apple':{'green': {'sweet':[1.5, 1.0]}, 
                   'yellow': {'sour':0.5},
                   'red':{'sweet':2.0}},
          'orange': {'orange':{'sour': 1.0,
                               'sweet': 1.2}},
          'banana':{'yellow': {'sweet': 1.0}}} 

My goal is to get a dictionary that keeps on updating the next option based on the previous choice of inputs for a dash app.我的目标是获得一个字典,该字典会根据之前对破折号应用程序的输入选择不断更新下一个选项。 I tried using collections.defaultdict but I could only do the first two columns.我尝试使用 collections.defaultdict 但我只能做前两列。

keys =A[:,0]
values = A[:,1:]
from collections import defaultdict
A_dict =defaultdict(list)
for ii, jj in zip(keys,values[:,0]):
    A_dict[ii].append(jj)

Edit: I tried the defaultdict method but I could not figure out a way to use all the columns.编辑:我尝试了 defaultdict 方法,但我无法找到使用所有列的方法。 I have a data that has more columns and rows, so wanted to automate the task.我有一个包含更多列和行的数据,因此想要自动执行该任务。

Thanks谢谢

Rather than having the value be a Union[int, List[int]] , the solution becomes a lot easier if its just a List[int] .与其将值设为Union[int, List[int]] ,不如将其设为List[int] [int] ,解决方案会变得容易得多。

Using this format we can easily use a defaultdict to create the data-structure.使用这种格式,我们可以轻松地使用 defaultdict 来创建数据结构。 The argument to the default dict is a function that creates a new value when a key is requested that is not yet assigned.默认 dict 的参数是 function 在请求尚未分配的键时创建一个新值。 So we can use a lambda to compose inner defaultdicts:所以我们可以使用 lambda 来组成内部默认字典:

from collections import defaultdict
import json

A = [['apple', 'green', 'sweet', 1.5],
     ['apple', 'green', 'sweet', 1.0],
     ['apple', 'red', 'sweet', 2.0],
     ['orange', 'orange', 'sour', 1.0],
     ['orange', 'orange', 'sweet', 1.2],
     ['apple', 'yellow', 'sour', 0.5],
     ['banana', 'yellow', 'sweet', 1.0]]

a_dict = defaultdict(lambda: defaultdict(lambda: defaultdict(list)))

for fruit, color, taste, val in A:
    a_dict[fruit][color][taste].append(val)


print(json.dumps(a_dict, indent=2))
{
  "apple": {
    "green": {
      "sweet": [
        1.5,
        1.0
      ]
    },
    "red": {
      "sweet": [
        2.0
      ]
    },
    "yellow": {
      "sour": [
        0.5
      ]
    }
  },
  "orange": {
    "orange": {
      "sour": [
        1.0
      ],
      "sweet": [
        1.2
      ]
    }
  },
  "banana": {
    "yellow": {
      "sweet": [
        1.0
      ]
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM