I have list of dict. which have same values for few keys. I want to make comma separated string of those keys,values which are common in dicts.
我有dict列表。对于几个键具有相同的值。我想用逗号分隔这些键的字符串,这些值在dicts中很常见。
Input:
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'}]
Output:
l=[{'name':'abc','role_no':30, 'class':'class-2, class3'}, {'name':'mnp','role_no':31,'class':'class-4'}]
1 个解决方案
#1
0
Here's a code that gives you what you want:
这是一个代码,可以为您提供所需内容:
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'}]
#1
0
Here's a code that gives you what you want:
这是一个代码,可以为您提供所需内容:
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'}]