Is there a Python dict without values?

后端 未结 3 1421
-上瘾入骨i
-上瘾入骨i 2021-01-07 19:02

Instead of this:

a = {\"foo\": None, \"bar\": None}

Is there a way to write this?

b = {\"foo\", \"bar\"}

相关标签:
3条回答
  • 2021-01-07 19:32

    Actually, in Python 2.7 and 3.2+, this really does work:

    >>> b = {"foo", "bar"}
    >>> b
    set(['foo', 'bar'])
    

    You can't use [] access on a set ("key into"), but you can test for inclusion:

    >>> 'x' in b
    False
    >>> 'foo' in b
    True
    

    Sets are as close to value-less dictionaries as it gets. They have average-case constant-time access, require hashable objects (i.e. no storing lists or dicts in sets), and even support their own comprehension syntax:

    {x**2 for x in xrange(100)}
    
    0 讨论(0)
  • 2021-01-07 19:34

    In order to "key" into a set in constant time use in:

    >>> s = set(['foo', 'bar', 'baz'])
    >>> 'foo' in s
    True
    >>> 'fork' in s
    False
    
    0 讨论(0)
  • 2021-01-07 19:43

    Yes, sets:

    set() -> new empty set object
    set(iterable) -> new set object
    
    Build an unordered collection of unique elements.
    

    Related: How is set() implemented?

    Time complexity : https://wiki.python.org/moin/TimeComplexity#set

    0 讨论(0)
提交回复
热议问题