根据字典中的值创建新列表

时间:2020-08-18 03:19:00

标签: python-3.x list dictionary

我有一个字典

{'Items': [
              {'stage': 'temp', 'file_status': 'NOT PROCESSED', 'table_name': 'abcd', 'filehour_key': '20200817-22'},
              {'stage': 'temp', 'file_status': 'NOT PROCESSED', 'table_name': 'abcd', 'filehour_key': '20200817-23'},
              {'stage': 'temp', 'file_status': 'NOT PROCESSED', 'table_name': 'efgh', 'filehour_key': '20200817-23'}
          ]
}

我想通过检查table_name来创建2个结果。

abcd_lst = [
               {'stage': 'temp', 'file_status': 'NOT PROCESSED', 'table_name': 'abcd', 'filehour_key': '20200817-22'},
               {'stage': 'temp', 'file_status': 'NOT PROCESSED', 'table_name': 'abcd', 'filehour_key': '20200817-23'}
           ]

efgh_lst = [
               {'stage': 'temp', 'file_status': 'NOT PROCESSED', 'table_name': 'efgh', 'filehour_key': '20200817-23'}
           ]

3 个答案:

答案 0 :(得分:1)

您本可以做一个简单的迭代来创建一个简单的列表字典。默认情况下,也可以这样做。


items = {'Items': [
              {'stage': 'temp', 'file_status': 'NOT PROCESSED', 'table_name': 'abcd', 'filehour_key': '20200817-22'},
              {'stage': 'temp', 'file_status': 'NOT PROCESSED', 'table_name': 'abcd', 'filehour_key': '20200817-23'},
              {'stage': 'temp', 'file_status': 'NOT PROCESSED', 'table_name': 'efgh', 'filehour_key': '20200817-23'}
          ]
}


import pprint
from collections import defaultdict

d = defaultdict(list)
for item in items['Items']:
    d[item['table_name']].append(item)

pprint.pprint(d)

答案 1 :(得分:1)

您可以轻松地遍历数据,将表存储在列表字典中(这有助于“捕获” dicts与相等的table_names,确保将它们配对/放置在一起。

下面是一个简单的代码,正是这样做的:

from collections import defaultdict
tables = defaultdict(list) # create a dict with list as default value
# iterate over 'Items' list 
for dct in it['Items']:
    table_name = dct.get('table_name') # get the name
    tables[table_name].append(dct)  # store in dict

# you can convert `tables` to a list    
tables = list(tables.values()) # a multi-dimensional list containing the two tables

# you can unpack tables  as well
table1, table2 = tables 

答案 2 :(得分:0)

尝试列表理解:

abcd_lst = [it for it in items['Items'] if it['table_name'] == 'abcd']
efgh_lst = [it for it in items['Items'] if it['table_name'] == 'efgh']

如果您的原始词典仅包含一个父键,那么这是一种不错的方法。

列表理解只是将for循环包装到一行中,这是一种简洁的方法。总体上是这样的:

对于任何原始的可迭代项(例如列表):

new_list = [<operation on element> for <element> in <original iterable>]

您也可以像上面一样添加可选的条件语句。