我有一份字典清单。它们对于少数几个键具有相同的值。我想用逗号分隔这些键的字符串,这些键是字典中常见的值。
输入:
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'}]发布于 2017-10-05 02:22:07
这是一段代码,它能给你想要的:
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'}]https://stackoverflow.com/questions/46571455
复制相似问题