📜  Python – 在字典列表中连接字符串值

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

Python – 在字典列表中连接字符串值

有时,在处理Python记录数据时,我们可能会遇到一个问题,即我们需要通过匹配特定键(如 ID)来执行键的字符串值的连接。这种问题可以在Web开发领域有应用。让我们讨论一下可以执行此任务的特定方式。

方法#1:使用循环
这是解决此问题的一种方法。在此,我们检查每个键,然后在相等键的基础上执行合并,并以蛮力方法执行特定所需键的连接。

# Python3 code to demonstrate working of 
# Concatenate String values in Dictionary List
# Using loop
  
# initializing list
test_list = [{'gfg' : "geeksfor", 'id' : 12, 'best' : (1, 2)}, 
            {'gfg' : "geeks", 'id' : 12, 'best' : (6, 2)},
            {'gfg' : "good", 'id' : 34, 'best' : (7, 2)}]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing compare key 
comp_key = 'id'
  
# initializing concat key 
conc_key = 'gfg'
  
# Concatenate String values in Dictionary List
# Using loop
res = []
for ele in test_list:
    temp = False
    for ele1 in res:
        if ele1[comp_key] == ele[comp_key]:
             ele1[conc_key] = ele1[conc_key] +  ele[conc_key]
             temp = True
             break
    if not temp:
         res.append(ele)
  
# printing result 
print("The converted Dictionary list : " + str(res)) 
输出 :