2017-10-04 38 views
0

我有字典列表。對於少數鍵具有相同的值。我想用逗號分隔這些鍵字符串,這些字符串在字典中是常見的。在Python中爲字典列表製作逗號分隔的字符串公共值字符串

輸入:

l = [{'name':'abc', 'role_no':30,'class':'class-2'},{'name':'abc','role_no':30, 'class':'class-3'},{'name':'mnp','role_no':31,'class':'class-4'}] 

輸出:

l=[{'name':'abc','role_no':30, 'class':'class-2, class3'}, {'name':'mnp','role_no':31,'class':'class-4'}] 

回答

0

這裏有你想要的東西,讓你一個代碼:

l = [{'name':'abc', 'role_no':30, 'class':'class-2'},{'name':'abc', 'role_no':30, 'class':'class-3'}] 

o = [{}] #output since you want a list of a dictionary 

for i in l: #For each dictionary 
    for j in i: #for each key in the dictionary 
     if j not in o[0]: #if the value of the key is not in o 
      o[0][j] = i[j] #add a new value to the output dictionary 
     elif o[0][j]==i[j]: #if the value is in o and matches the value already there 
      pass 
     else: #if the value is in o and doesn't match the value already there 
      o[0][j]+= ", " + (i[j]) #otherwise add it to the string of the value that is there 

print(o) #[{'name': 'abc', 'role_no': 30, 'class': 'class-2, class-3'}] 
+0

感謝。它只適用於普通字典。我編輯了輸入(不工作) –