Making a set from dictionary values

落爺英雄遲暮 提交于 2020-01-21 08:35:17

问题


I want to create a set from the values of an existing dict

def function(dictionary):
    ... 
    return set_of_values

Say my dictionary looks like this: {'1': 'Monday', '2': 'Tuesday', '3': 'Monday'}

I want a set returned that only contains the unique values, like this:

{'Monday', 'Tuesday'}

回答1:


For Python:

set(d.values())

Equivalent on Python 2.7:

set(d.viewvalues())

If you need a cross-compatible Python 2.7/3.x code:

{d[k] for k in d}



回答2:


Just another way to unique out:

 >>> my_dict = {'1': 'Monday', '3': 'Monday', '2': 'Tuesday'}
 >>> {y:x for x,y in my_dict.iteritems()}.keys()
 ['Tuesday', 'Monday']
 >>>


来源:https://stackoverflow.com/questions/27239501/making-a-set-from-dictionary-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!