简体   繁体   English

对字典中的列表值使用sort和set()

[英]using sort and set() on list values in dictionary

I have a dictionary which has single value as key and a list as the value. 我有一本字典,其中的单个值作为键,而列表则作为值。 I am trying to go through the dictionary values and remove duplicates and sort the lists. 我正在尝试浏览字典值并删除重复项并对列表进行排序。 Im using the below code to try this. 林使用下面的代码来尝试这一点。

def activity_time_from_dict(adict):
    for v in adict.values():
        v = list(set(v))
        v.sort()

From printing within the loop it seems to do it correctly, but if I look at the dictionary outside of the loop it has just been sorted and the duplicates remain. 从循环内打印看来,它似乎是正确的,但是如果我看一下循环外的字典,它刚刚被排序,重复项仍然保留。 I want to replace the original list in the dictionary with the seted and sorted list. 我想用已设置和排序的列表替换字典中的原始列表。 What am I doing wrong ? 我究竟做错了什么 ?

Use slice assignment 使用切片分配

 v[:] = list(set(v))
 # v[:] = set(v)  has the same effect

to mutate the object and not just reassign the loop variable. 改变对象,而不仅仅是重新分配循环变量。 Or more obviously, rebind to the same key: 或更明显的是,重新绑定到相同的密钥:

for k in adict:
    adict[k] = sorted(set(adict[k]))
In [1]: dd = {'a':[1, 3, -5, 2, 3, 1]}

In [2]: for i in dd:sorted(list(set(dd['a'])))

In [3]: for i in dd:
    ...:     dd[i] = sorted(list(set(dd[i])))
    ...:     

In [4]: dd
Out[4]: {'a': [-5, 1, 2, ]}

you can try this 你可以试试这个

def dict(adict):
    for v in adict.values():
        v = list(set(v))
        v.sort()
        return v

new_dict['your_key']=dict(old_dict)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM