从字典列表中提取具有给定键的字典的Python程序
给定字典列表,任务是编写一个Python程序,该程序仅提取包含特定给定键值的那些字典。
Input : test_list = [{‘gfg’ : 2, ‘is’ : 8, ‘good’ : 3}, {‘gfg’ : 1, ‘for’ : 10, ‘geeks’ : 9}, {‘love’ : 3}], key= “gfg”
Output : [{‘gfg’: 2, ‘is’: 8, ‘good’: 3}, {‘gfg’ : 1, ‘for’ : 10, ‘geeks’ : 9}]
Explanation : gfg is present in first two dictionaries, hence extracted.
Input : test_list = [{‘gfg’ : 2, ‘is’ : 8, ‘good’ : 3}, {‘gfg’ : 1, ‘for’ : 10, ‘geeks’ : 9}, {‘love’ : 3, ‘gfgs’ : 4}], key = “good”
Output : [{‘gfg’: 2, ‘is’: 8, ‘good’: 3}]
Explanation : good is present in 1st dictionary, hence extracted.
方法 1:使用列表理解和keys()
在此,我们使用in 运算符测试密钥是否存在,使用 key() 提取密钥。列表理解用于迭代不同的字典。
例子:
Python3
# Python3 code to demonstrate working of
# Extract Dictionaries with given Key
# Using list comprehension + keys()
# initializing list
test_list = [{'gfg': 2, 'is': 8, 'good': 3},
{'gfg': 1, 'for': 10, 'geeks': 9},
{'love': 3}]
# printing original list
print("The original list is : " + str(test_list))
# initializing key
key = 'gfg'
# checking for key using in operator
# keys() used to get keys
res = [sub for sub in test_list if key in list(sub.keys())]
# printing result
print("The filtered Dictionaries : " + str(res))
Python3
# Python3 code to demonstrate working of
# Extract Dictionaries with given Key
# Using filter() + lambda
# initializing list
test_list = [{'gfg': 2, 'is': 8, 'good': 3},
{'gfg': 1, 'for': 10, 'geeks': 9},
{'love': 3, 'gfg': 4}]
# printing original list
print("The original list is : " + str(test_list))
# initializing key
key = 'good'
# checking for key using in operator
# keys() used to get keys
# filter() + lambda used to perform fileration
res = list(filter(lambda sub: key in list(sub.keys()), test_list))
# printing result
print("The filtered Dictionaries : " + str(res))
输出:
The original list is : [{‘gfg’: 2, ‘is’: 8, ‘good’: 3}, {‘gfg’: 1, ‘for’: 10, ‘geeks’: 9}, {‘love’: 3}]
The filtered Dictionaries : [{‘gfg’: 2, ‘is’: 8, ‘good’: 3}, {‘gfg’: 1, ‘for’: 10, ‘geeks’: 9}]
方法 2:使用filter()和lambda
在这里,我们使用 filter() 执行过滤任务,并且使用 lambda函数将逻辑注入过滤。 in运算符用于检查特定键的存在。
例子:
蟒蛇3
# Python3 code to demonstrate working of
# Extract Dictionaries with given Key
# Using filter() + lambda
# initializing list
test_list = [{'gfg': 2, 'is': 8, 'good': 3},
{'gfg': 1, 'for': 10, 'geeks': 9},
{'love': 3, 'gfg': 4}]
# printing original list
print("The original list is : " + str(test_list))
# initializing key
key = 'good'
# checking for key using in operator
# keys() used to get keys
# filter() + lambda used to perform fileration
res = list(filter(lambda sub: key in list(sub.keys()), test_list))
# printing result
print("The filtered Dictionaries : " + str(res))
输出:
The original list is : [{‘gfg’: 2, ‘is’: 8, ‘good’: 3}, {‘gfg’: 1, ‘for’: 10, ‘geeks’: 9}, {‘love’: 3, ‘gfg’: 4}]
The filtered Dictionaries : [{‘gfg’: 2, ‘is’: 8, ‘good’: 3}]