从字典值中创建一个集合

Making a set from dictionary values(从字典值中创建一个集合)

本文介绍了从字典值中创建一个集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

解决方案

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}

这篇关于从字典值中创建一个集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:从字典值中创建一个集合