【问题标题】:How to make comma separated string from same values of dictionary如何使逗号分隔的字符串与字典的相同值
【发布时间】:2017-10-04 18:09:34
【问题描述】:

我有字典列表。对于几个键具有相同的值。我想用逗号分隔这些键值,字典中常见的值。

输入:

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'}]

【问题讨论】:

    标签: python-2.7 list dictionary


    【解决方案1】:

    这里有一个代码,可以满足您的需求:

    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'}]
    

    【讨论】:

    • 谢谢。它仅适用于常见的字典。我已经编辑了输入(不工作)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-09
    • 1970-01-01
    • 1970-01-01
    • 2020-02-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多