我有一本使用一系列 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'
是将空值传递到 item
的结果的初始状态。然后'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
的问题对于后续的唯一项目,以及(ii)我需要列表保持有序 - 因此,简单地迭代末尾的所有内容并强制列表中的元素数量达到给定数量对我没有任何好处。
感谢任何帮助。
最佳答案
字典理解是一个很好的解决方案,并且是纯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]
}
}
关于Python - 迭代列表字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50891784/