📜  Python – 将嵌套字典展平为矩阵

📅  最后修改于: 2022-05-13 01:54:58.183000             🧑  作者: Mango

Python – 将嵌套字典展平为矩阵

有时,在处理数据时,我们可能会遇到需要将嵌套字典转换为矩阵的问题,每个嵌套由矩阵中的不同行组成。这可以在许多数据域中应用。让我们讨论可以执行此任务的某些方式。
方法 #1:使用循环 + zip() + map()
上述功能的组合可用于执行此任务。在此,我们使用蛮力来展平字典键,然后使用 map() 和 zip() 将它们对齐为矩阵行。

Python3
# Python3 code to demonstrate working of
# Flatten Nested Dictionary to Matrix
# using zip() + loop + map()
   
# initializing dictionary
test_dict = {'Gfg1' : {'CS':1, 'GATE' : 2},
             'Gfg2' : {'CS':2, 'GATE' : 3},
             'Gfg3' : {'CS':4, 'GATE' : 5}}
   
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Flatten Nested Dictionary to Matrix
# using zip() + loop + map()
temp = list(test_dict.values())
sub = set()
for ele in temp:
    for idx in ele:
        sub.add(idx)
res = []
res.append(sub)
for key, val in test_dict.items():
    temp2 = []
    for idx in sub:
        temp2.append(val.get(idx, 0))
    res.append(temp2)
 
res = [[idx for idx, val in test_dict.items()]] + list(map(list, zip(*res)))
   
# printing result 
print("The Grouped dictionary list is : " + str(res))


Python3
# Python3 code to demonstrate working of
# Flatten Nested Dictionary to Matrix
# using union() + list comprehension
   
# initializing dictionary
test_dict = {'Gfg1' : {'CS':1, 'GATE' : 2},
             'Gfg2' : {'CS':2, 'GATE' : 3},
             'Gfg3' : {'CS':4, 'GATE' : 5}}
   
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Flatten Nested Dictionary to Matrix
# using union() + list comprehension
temp = set().union(*test_dict.values())
res = [list(test_dict.keys())]
res += [[key] + [sub.get(key, 0) for sub in test_dict.values()] for key in temp]
   
# printing result 
print("The Grouped dictionary list is : " + str(res))


输出 :

原始字典是:{'Gfg3': {'GATE': 5, 'CS': 4}, 'Gfg1': {'GATE': 2, 'CS': 1}, 'Gfg2': {'GATE' :3,'CS':2}}
分组字典列表为:[['Gfg3', 'Gfg1', 'Gfg2'], ['GATE', 5, 2, 3], ['CS', 4, 1, 2]]


方法 #2:使用 union() + 列表推导
上述方法的组合可用于执行此任务。在此,我们使用 union() 而不是嵌套循环来计算联合。结果是使用列表推导编译的。

Python3

# Python3 code to demonstrate working of
# Flatten Nested Dictionary to Matrix
# using union() + list comprehension
   
# initializing dictionary
test_dict = {'Gfg1' : {'CS':1, 'GATE' : 2},
             'Gfg2' : {'CS':2, 'GATE' : 3},
             'Gfg3' : {'CS':4, 'GATE' : 5}}
   
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Flatten Nested Dictionary to Matrix
# using union() + list comprehension
temp = set().union(*test_dict.values())
res = [list(test_dict.keys())]
res += [[key] + [sub.get(key, 0) for sub in test_dict.values()] for key in temp]
   
# printing result 
print("The Grouped dictionary list is : " + str(res))
输出 :

原始字典是:{'Gfg3': {'GATE': 5, 'CS': 4}, 'Gfg1': {'GATE': 2, 'CS': 1}, 'Gfg2': {'GATE' :3,'CS':2}}
分组字典列表为:[['Gfg3', 'Gfg1', 'Gfg2'], ['GATE', 5, 2, 3], ['CS', 4, 1, 2]]