从嵌套键中提取字典值,留下主键,然后转换为列表


a = {
1: {'abc': 50, 'def': 33, 'xyz': 40},
2: {'abc': 30, 'def': 22, 'xyz': 45},
3: {'abc': 15, 'def': 11, 'xyz': 50}
}

我想遍历这个嵌套字典,删除子键(或提取子键值),但保留主键。第二步是将字典转换为列表的列表:

b = [
[1, 50, 33, 40],
[2, 30, 22, 45],
[3, 15, 11, 50]
]

我浏览了这里谈论提取键和值的无数帖子,但找不到一个足够接近的例子来适合我需要的(这仍然是新的):到目前为止,我有这个:

for key in a.keys():
if type(a[key]) == dict:
a[key] = a[key].popitem()[1]

给出了这个-每个键中的第三个子键的值:它是一个开始,但不是完整的或我想要的

{1: 40, 2: 45, 3: 50}

a.items()上使用列表推导,使用dict.values()获得值,然后您可以使用解包(*)获得所需的列表。

>>> [[k, *v.values()] for k,v in a.items()]
[[1, 50, 33, 40], [2, 30, 22, 45], [3, 15, 11, 50]]

这个解决方案可能不是最优雅的解决方案,但它确实满足了您的需求:

a = {
1: {'abc': 50, 'def': 33, 'xyz': 40},
2: {'abc': 30, 'def': 22, 'xyz': 45},
3: {'abc': 15, 'def': 11, 'xyz': 50}
}
b = []
for key1, dict2 in a.items():
c = [key1]
c.extend(dict2.values())
b.append(c)
print(b)

相关内容

最新更新