Python - 条件连接字典列表
给定 2 个字典列表,任务是编写一个Python程序来执行条件连接,即添加键,基于相似索引字典中特定键的相似性。
例子:
Input : test_list1 = [{“gfg” : 1, “is” : 3, “best”: 2}, {“gfg” : 1, “best” : 6}, {“all” : 7, “best” : 10} ],
test_list2 = [{“good” : 4, “best”: 2}, {“geeks” : 2, “best” : 3 }, {“CS” : 2, “best” : 10 } ], test_key = “best”
Output : [{‘gfg’: 1, ‘is’: 3, ‘best’: 2, ‘good’: 4}, {‘gfg’: 1, ‘best’: 6}, {‘all’: 7, ‘best’: 10, ‘CS’: 2}]
Explanation : best has 2 in both dictionaries of 0th index, hence at index 0, dictionaries are merged.
Input : test_list1 = [{“gfg” : 1, “is” : 3, “best”: 3}, {“gfg” : 1, “best” : 6}, {“all” : 7, “best” : 10} ],
test_list2 = [{“good” : 4, “best”: 2}, {“geeks” : 2, “best” : 3 }, {“CS” : 2, “best” : 10 } ], test_key = “best”
Output : [{‘gfg’: 1, ‘is’: 3, ‘best’: 3}, {‘gfg’: 1, ‘best’: 6}, {‘all’: 7, ‘best’: 10, ‘CS’: 2}]
Explanation : best has 10 in both dictionaries of 2nd index, hence at index 2, dictionaries are merged.
方法:使用next() + update()
在这里,我们使用生成器表达式来检查字典的键是否与相似的索引字典键匹配,如果是,则使用 update() 合并所有对应的键。
Python3
# Python3 code to demonstrate working of
# Conditional Join Dictionary List
# Using update() + next()
# initializing lists
test_list1 = [{"gfg": 1, "is": 3, "best": 2}, {
"gfg": 1, "best": 6}, {"all": 7, "best": 10}]
test_list2 = [{"good": 4, "best": 2}, {
"geeks": 2, "best": 3}, {"CS": 2, "best": 10}]
# printing original list
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# initializing test key
test_key = "best"
for sub1 in test_list1:
# checking for matching key
temp = next(
(itm for itm in test_list2 if sub1[test_key] == itm[test_key]), None)
if(temp):
# performing update
sub1.update(temp)
# printing result
print("Joined result : " + str(test_list1))
输出:
The original list 1 is : [{‘gfg’: 1, ‘is’: 3, ‘best’: 2}, {‘gfg’: 1, ‘best’: 6}, {‘all’: 7, ‘best’: 10}]
The original list 2 is : [{‘good’: 4, ‘best’: 2}, {‘geeks’: 2, ‘best’: 3}, {‘CS’: 2, ‘best’: 10}]
Joined result : [{‘gfg’: 1, ‘is’: 3, ‘best’: 2, ‘good’: 4}, {‘gfg’: 1, ‘best’: 6}, {‘all’: 7,
‘best’: 10, ‘CS’: 2}]