Is There a Python Dict Without Values?

Is There a Python Dict Without Values?

Instead of this:

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

Is there a way to write this?

b = {"foo", "bar"}

And still let b have constant time access (i.e. not a Python set, which cannot be keyed into)?

11

3 Answers

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)}
2

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 :

1

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
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sarah Jenkins
Author

Sarah Jenkins

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.