首页 > 解决方案 > Python - 遍历列表字典

问题描述

我有一个使用一系列for循环生成的字典。结果如下所示:

{
'item1': {
    'attribute1': [3],
    'attribute2': [2],
    'attribute3': [False],
    },
'item2': {
    'attribute1': [2, 5, 2],
    'attribute2': [3, 2, 8],
    'attribute3': [False, 7, False],
    },
'item3': {
    'attribute1': [8],
    'attribute2': [4],
    'attribute3': [False],
    },
}

显示False'attribute3'将一个空值传递给items 初始状态的结果。然后'item2'通过另外两次迭代进行更新。

我想做的是让每个属性的列表长度相同,以便所需的输出是:

{
'item1': {
    'attribute1': [3, False, False],
    'attribute2': [2, False, False],
    'attribute3': [False, False, False],
    },
'item2': {
    'attribute1': [2, 5, 2],
    'attribute2': [3, 2, 8],
    'attribute3': [False, 7, False],
    },
'item3': {
    'attribute1': [8, False, False],
    'attribute2': [4, False, False],
    'attribute3': [False, False, False],
    },
}

作为参考 - 初始条目的代码检查以确保它item_desc是唯一的,如果是,则生成一个新条目 - 它看起来像这样:

record.update({item_desc: {
    'attribute1':[],
    'attribute2':[],
    'attribute3':[],
    }})
for key, value in [
    ('attribute1', value1),
    ('attribute2', value2),
    ('attribute3', value3)]:
    record[item_desc][key].append(value)

如果'item_desc'不是唯一的,则'for key, value in...'针对非唯一项再次运行'item_desc',并将新属性值附加到现有项目。

我尝试了什么......好吧,我尝试在找到唯一项目时迭代“记录”对象并使用以下内容附加一个 False 值:

for item in record:
    for key in ['attribute1', 'attribute2', 'attribute3']:
    record[item][key].append(False)

但是(i)它不能解决为False后续唯一项目添加 a 的问题,并且(ii)我需要列表保持有序 - 所以在最后简单地遍历所有内容并强制到 a 对我没有任何好处给定列表的元素数量。

任何帮助表示赞赏。

标签: pythonpython-3.x

解决方案


dict理解是一个很好的解决方案和纯python。

仅出于选择的考虑,您还可以使用诸如pandas.

df = pd.DataFrame(d)
max_ = df.max().str.len().max() # max length (in this case, 3)
df.transform(lambda x: [z + [False]*(max_ - len(z)) for z in x]).to_dict()

输出

{'item1': 
    {'attribute1': [3, False, False],
     'attribute2': [2, False, False],
     'attribute3': [False, False, False]
    },
 'item2': 
    {'attribute1': [2, 5, 2],
     'attribute2': [3, 2, 8],
     'attribute3': [False, 7, False]
     },
 'item3': 
    {'attribute1': [8, False, False],
     'attribute2': [4, False, False],
     'attribute3': [False, False, False]
    }
}

推荐阅读