我有一本字典,是用一系列
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
s初始状态。那么
'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...'
对非唯一的
'项目描述'
新的属性值被附加到现有的项中。
我试过什么…好吧,我尝试在找到唯一项时迭代“record”对象,并使用如下方式附加一个假值:
for item in record:
for key in ['attribute1', 'attribute2', 'attribute3']:
record[item][key].append(False)
但(i)添加
错误
对于随后的唯一项和(i i)我需要列表保持有序-所以简单地遍历末尾的所有内容并强制为列表指定数量的元素对我没有任何好处。
感谢您的帮助。