Python - 迭代列表字典

标签 python python-3.x

我有一本使用一系列 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/

相关文章:

python - 我可以将 Papermill 和 Scrapbook 与 AWS EMR Notebooks 结合使用吗?

python - 如何跨分区平衡我的数据?

python - Pyspark - 计算每个数据框列中的空值数

python - python 警告 conda.common.logic :get_sat_solver_cls(278)

python - 在尝试组合两个数组时,我在 numpy 中遇到类型问题

python - App Engine 批量数据上传 URLError : "Connection reset by peer"

python - 跳过文件的某些字节并返回内容

python - 我想在 PyQt 的某个列中将两个 lineEdit 信息添加到 csv

sql - 如何过滤 Django 模型以仅包含出现在子表(带有外键)中的模型?

python - 在python中的其他列条件下获取数据框中列的唯一值