简体   繁体   中英

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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