📜  用于创建包含字典列表中所有键的子字典的Python程序

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

用于创建包含字典列表中所有键的子字典的Python程序

给定字典列表,我们的任务是创建一个包含所有键的新字典列表,如果没有,则将 None 分配给每个字典的键并持久化。

例子:

方法 #1:使用set() + chain.from_iterable() + get() +列表理解

在此,我们使用 set() 和 chain.from_iterable() 执行获取所有必需密钥的任务。下一步是使用列表理解和 get() 更新所有未找到键的字典。

Python3
# Python3 code to demonstrate working of
# Ensure all keys in dictionary list
# Using set() + chain.from_iterable() + get() + list comprehension
from itertools import chain
  
# initializing list
test_list = [{'gfg' : 3, 'is' : 7}, 
             {'gfg' : 3, 'is' : 1, 'best' : 5}, 
             {'gfg' : 8}]
               
# printing original list
print("The original list is : " + str(test_list))
  
# extracting all keys
all_keys = set(chain.from_iterable(test_list))
  
# assigning None using get() if key's value is not found
res = [dict((key, sub.get(key, None)) for key in all_keys) for sub in test_list]
  
# printing result
print("Reformed dictionaries list : " + str(res))


Python3
# Python3 code to demonstrate working of
# Ensure all keys in dictionary list
# Using set() + chain.from_iterable() + update()
from itertools import chain
  
# initializing list
test_list = [{'gfg' : 3, 'is' : 7}, 
             {'gfg' : 3, 'is' : 1, 'best' : 5}, 
             {'gfg' : 8}]
               
# printing original list
print("The original list is : " + str(test_list))
  
# extracting all keys
all_keys = set(chain.from_iterable(test_list))
  
# assigning None using update() if key is not found 
for sub in test_list:
    sub.update({key: None for key in all_keys if key not in sub})
  
# printing result
print("Reformed dictionaries list : " + str(test_list))


输出:

方法 #2:使用 set() + chain.from_iterable() + update()

其中,字典中所有键的更新和检查是使用 update() 完成的,其余所有功能保持相似。

蟒蛇3

# Python3 code to demonstrate working of
# Ensure all keys in dictionary list
# Using set() + chain.from_iterable() + update()
from itertools import chain
  
# initializing list
test_list = [{'gfg' : 3, 'is' : 7}, 
             {'gfg' : 3, 'is' : 1, 'best' : 5}, 
             {'gfg' : 8}]
               
# printing original list
print("The original list is : " + str(test_list))
  
# extracting all keys
all_keys = set(chain.from_iterable(test_list))
  
# assigning None using update() if key is not found 
for sub in test_list:
    sub.update({key: None for key in all_keys if key not in sub})
  
# printing result
print("Reformed dictionaries list : " + str(test_list))

输出: