首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从字典的相同值中生成逗号分隔的字符串

如何从字典的相同值中生成逗号分隔的字符串
EN

Stack Overflow用户
提问于 2017-10-05 02:09:35
回答 1查看 737关注 0票数 0

我有一份字典清单。它们对于少数几个键具有相同的值。我想用逗号分隔这些键的字符串,这些键是字典中常见的值。

输入:

代码语言:javascript
复制
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'}]

输出:

代码语言:javascript
复制
l=[{'name':'abc','role_no':30, 'class':'class-2, class3'}, {'name':'mnp','role_no':31,'class':'class-4'}]
EN

回答 1

Stack Overflow用户

发布于 2017-10-05 02:22:07

这是一段代码,它能给你想要的:

代码语言:javascript
复制
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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46571455

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档