如何翻译字典的列表介绍字典列表?

时间:2019-05-18 15:04:09

标签: python

所以我需要在词典中的词典中创建一些词典...我真的可以使用帮助来编写它。我试图弄清楚,但我无法通过创建第三个字典的操作。

所以我有一个列表列表,其中包含我的数据,看起来像这样:

my_data = [['Floor_one', 'Working', 'Dogs', 'May', '2000'],
['Floor_one', 'Jobless', 'Cats', 'June', '3000'], 
['Floor_two', 'Working', 'Dogs', 'May', '2100'],
['Floor_two', 'Jobless', 'Cats', 'June', '2200'],
['Floor_three', 'Working', 'Dogs', 'May', '2300'],
['Floor_three', 'Working', 'Cats', 'June', '4500']]

我需要从看起来像这样的列表列表中创建一个字典:

my_dict = {Floor: {Month: {Working:{Dogs:200, Cats: 300}, Jobless:{Dogs:200, Cats: 300}

所以在我看来,它应该像这样:

my_dict = {Floor_one: 
{May: {Working:{Dogs:200, Cats: 300}, Jobless:{Dogs:200, Cats: 300}, 
June: {Working:{Dogs:200, Cats: 300}, Jobless:{Dogs:200, Cats: 300}
{Floor_two: 
{May: {Working:{Dogs:800, Cats: 400}, Jobless:{Dogs:1000, Cats: 3300}, 
June: {Working:{Dogs:700, Cats: 500}, Jobless:{Dogs:2100, Cats: 2300}

当然,我的清单列表大得多,如300行,我的楼层和月份也更多。 我当前的代码如下所示:

def my_function(our_data) # our data is my list of lists
    for line in our_data[1:]: #ignore first line since is name of columns
            if line[0] not in nested_dict:
                nested_dict[line[0]] = 0
    return nested_dict

它创造了我的地板,但我不知道该怎么走。 有人可以帮我吗? :)我正在这样做,所以我可以找出我在X东西上花了多少钱,并有特别的敬意。例如,我要求输入(Floor_one,May,Working,Cats),响应为300

2 个答案:

答案 0 :(得分:0)

如果我是你,我会重新考虑我的数据结构。这非常复杂,您应该尝试使其更易于使用。也许首先要从dict开始。无论如何,这可能会帮助您:

In [15]: d = [["floor_one", "working", "dogs", "may", 2000], ["floor_one", "jobless", "cats", "june", 3000], ["floor_
    ...: two", "working", "dogs", "may", 2100]]
    ...:
    ...: import collections
    ...:
    ...: new_d = collections.defaultdict(dict)
    ...:
    ...: for l in d:
    ...:     inner_inner_local_d = {}
    ...:     inner_inner_local_d[l[2]] = l[4]
    ...:     inner_local_d = {}
    ...:     inner_local_d[l[1]] = inner_inner_local_d
    ...:     new_d[l[0]][l[3]] = inner_local_d
    ...:

In [16]: new_d
Out[16]:
defaultdict(dict,
            {'floor_one': {'may': {'working': {'dogs': 2000}},
              'june': {'jobless': {'cats': 3000}}},
             'floor_two': {'may': {'working': {'dogs': 2100}}}})

答案 1 :(得分:-1)

我建议保持数据不变,并运行查询以检查某些属性的存在。

my_data = [
    ['Floor_one', 'Working', 'Dogs', 'May', 2000],
['Floor_one', 'Jobless', 'Cats', 'June', 3000], 
['Floor_two', 'Working', 'Dogs', 'May', 2100],
['Floor_two', 'Jobless', 'Cats', 'June', 2200],
['Floor_three', 'Working', 'Dogs', 'May', 2300],
['Floor_three', 'Working', 'Cats', 'June', 4500]
]

def query_volumes (query, data):
    for q in query:
        data = [d for d in data if q in d]
    volumes = [d[-1] for d in data]
    return sum(volumes)

query1 = ['Floor_three', 'June', 'Working', 'Cats']
query2 = ['Cats']

query_volumes(query1, my_data)
# RETURNS 4500
query_volumes(query2, my_data)
# RETURNS 9700