小编viv*_*ian的帖子

在python3中反转字典中的键和值(值不唯一)

我知道当值是唯一的时,如何简单地在字典中反转键和值.但是当值不唯一时如何反转.根据要求,如果值出现不止一次,我需要使用set来将它们组合在一起.


防爆.输入d = {'a':1, 'b':2,'c':1,'d':2}输出d = {1,{'a','c'},2,{'b','c'}}


我在下面编写了相当愚蠢的代码,但因为我只创建了一个集合,因此所有显示多次的值都在该集合中.

def change(d):

    inverted_l = list(map(lambda t:(t[1],t[0]), d.items()))
    store_key = [] #for store the key to check if value appear more than one
    new_d = {}
    x = set()
    for i in range(len(inverted_l)):
        store_key.append(inverted_l[i][0])
    for i in range(len(store_key)):
        if store_key.count(store_key[i])> 1:
            x.add(inverted_l[i][1]) #I think the problem is I need create set
                                    #each time, but I don't know how to do that
            new_d[store_key[i]] = x
        else:
            new_d[store_key[i]] = inverted_l[i][1]
    return new_d …
Run Code Online (Sandbox Code Playgroud)

python dictionary duplicates key-value python-3.x

3
推荐指数
1
解决办法
571
查看次数

标签 统计

dictionary ×1

duplicates ×1

key-value ×1

python ×1

python-3.x ×1