python - 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'
将一个空值传递给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...'
针对非唯一项再次运行'item_desc'
,并将新属性值附加到现有项目。
我尝试了什么......好吧,我尝试在找到唯一项目时迭代“记录”对象并使用以下内容附加一个 False 值:
for item in record:
for key in ['attribute1', 'attribute2', 'attribute3']:
record[item][key].append(False)
但是(i)它不能解决为False
后续唯一项目添加 a 的问题,并且(ii)我需要列表保持有序 - 所以在最后简单地遍历所有内容并强制到 a 对我没有任何好处给定列表的元素数量。
任何帮助表示赞赏。
解决方案
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]
}
}
推荐阅读
- android - 尝试清除()arraylist时自动添加arraylist并出错
- ios - 如何将当前时间增加 5 分钟
- gpu - 播放 360 视频并弹出 UI(钴)时如何合成 UI 和 360 视频
- php - 如何重命名codeigniter重命名文件夹中的文件夹不起作用
- windows - 批处理脚本 - 将 systeminfo 命令的输出保存到变量
- javascript - 如何根据 id 显示特定的 div,id 将是动态的
- module - 将字段添加到 joomla 3.8 登录表单
- python - 就 a 和 b 而言,以下算法的运行时复杂度是多少?
- powershell - 如何在 csv 中获取 ADUser 的 Groupmembership
- mysql - MYSQL 选择日期最近的记录