📜  Python - 在 K 键中提取具有空字符串值的字典

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

Python - 在 K 键中提取具有空字符串值的字典

给定字典列表,提取所有具有空字符串的字典作为特定键的值。

方法#1:使用列表理解

这是可以执行此任务的方法之一。在这里,我们在所有字典中运行一个循环并检查键的空字符串值。所有这些都是在列表理解而不是循环中编译的。

Python3
# Python3 code to demonstrate working of 
# Extract dictionaries with Empty String value in K key
# Using list comprehension
  
# initializing lists
test_list = [{"Gfg" : "4", "is" : "good", "best" : "1"},
             {"Gfg" : "", "is" : "better", "best" : "8"},
             {"Gfg" : "9", "is" : "CS", "best" : "10"}]
  
# printing original list
print("The original list : " + str(test_list))
  
# initializing K key 
K = "Gfg"
  
# using list comprehension to fetch empty string key's dictionaries
res = [sub for sub in test_list if sub[K] == '']
      
# printing result 
print("The extracted dictionaries : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Extract dictionaries with Empty String value in K key
# Using filter() + lambda
  
# initializing lists
test_list = [{"Gfg" : "4", "is" : "good", "best" : "1"},
             {"Gfg" : "", "is" : "better", "best" : "8"},
             {"Gfg" : "9", "is" : "CS", "best" : "10"}]
  
# printing original list
print("The original list : " + str(test_list))
  
# initializing K key 
K = "Gfg"
  
# filter() used to iteration
# lambda for functionality
res = list(filter(lambda sub: sub[K] == '', test_list))
      
# printing result 
print("The extracted dictionaries : " + str(res))


输出
The original list : [{'Gfg': '4', 'is': 'good', 'best': '1'}, {'Gfg': '', 'is': 'better', 'best': '8'}, {'Gfg': '9', 'is': 'CS', 'best': '10'}]
The extracted dictionaries : [{'Gfg': '', 'is': 'better', 'best': '8'}]

方法 #2:使用 filter() + lambda

这是可以执行此任务的另一种方式。在此,我们使用 filter() 和功能以及 lambda 迭代提取所有空值键的字典。

蟒蛇3

# Python3 code to demonstrate working of 
# Extract dictionaries with Empty String value in K key
# Using filter() + lambda
  
# initializing lists
test_list = [{"Gfg" : "4", "is" : "good", "best" : "1"},
             {"Gfg" : "", "is" : "better", "best" : "8"},
             {"Gfg" : "9", "is" : "CS", "best" : "10"}]
  
# printing original list
print("The original list : " + str(test_list))
  
# initializing K key 
K = "Gfg"
  
# filter() used to iteration
# lambda for functionality
res = list(filter(lambda sub: sub[K] == '', test_list))
      
# printing result 
print("The extracted dictionaries : " + str(res))
输出
The original list : [{'Gfg': '4', 'is': 'good', 'best': '1'}, {'Gfg': '', 'is': 'better', 'best': '8'}, {'Gfg': '9', 'is': 'CS', 'best': '10'}]
The extracted dictionaries : [{'Gfg': '', 'is': 'better', 'best': '8'}]