📜  Python – 值列表键展平

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

Python – 值列表键展平

有时,在使用Python字典时,我们可能会遇到一个问题,即我们需要对每个键值执行配对以提取扁平字典。这类问题可以在数据域中应用。让我们讨论可以执行此任务的特定方式。

方法#1:使用循环
这是可以执行此任务的粗暴方式。在此,我们迭代每个键的值并将其分配给它的键并构造新的键值对。

# Python3 code to demonstrate working of 
# Value List Key Flattening
# Using loop
  
# initializing dictionary
test_dict = {'gfg' : [4, 5, 7], 'best' : [10, 12]}
  
# printing original dictionary
print("The original dictionary : " + str(test_dict))
  
# Value List Key Flattening
# Using loop
res = []
for key, vals in test_dict.items():
    for ele in vals:
        res.append({"key": key, "value": ele})
  
# printing result 
print("The flattened dictionary : " + str(res)) 
输出 :
The original dictionary : {'best': [10, 12], 'gfg': [4, 5, 7]}
The flattened dictionary : [{'value': 10, 'key': 'best'}, {'value': 12, 'key': 'best'}, {'value': 4, 'key': 'gfg'}, {'value': 5, 'key': 'gfg'}, {'value': 7, 'key': 'gfg'}]