Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)?

like image 529
nucleartide Avatar asked Oct 18 '13 16:10

nucleartide


People also ask

Can you have a dictionary with no values in Python?

Restrictions on Dictionary ValuesLiterally none at all. A dictionary value can be any type of object Python supports, including mutable types like lists and dictionaries, and user-defined objects, which you will learn about in upcoming tutorials.

Can a dictionary have a key without a value?

You can add a new key to the dictionary without value using the None keyword. It'll just add a new key to the dictionary.

Can a dictionary key have empty value Python?

In Python, we can use the zip() and len() methods to create an empty dictionary with keys. This method creates a dictionary of keys but returns no values from the dictionary.


2 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)} 
like image 121
nneonneo Avatar answered Oct 13 '22 16:10

nneonneo


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

like image 45
Ashwini Chaudhary Avatar answered Oct 13 '22 16:10

Ashwini Chaudhary