Re:PEP 584 – Add + and – operators to the built-in dict class
by cube2222 on Wednesday March 06, 2019 @04:36AM
(#19317558)
Same as Go, where everybody just uses map[Key]struct{} as sets.
Re:PEP 584 – Add + and – operators to the built-in dict class
by bpicolo on Wednesday March 06, 2019 @04:43AM
(#19317595)
To be fair, this is because the language does not support a type safe set type. I would use one frequently if it did
Re:PEP 584 – Add + and – operators to the built-in dict class
by majewsky on Wednesday March 06, 2019 @01:11PM
(#19321092)
map[T]struct{} is a type-safe set type. It's just not an ergonomic one.
FWIW, I'm usually using map[T]bool and only ever inserting `true` values. It uses a bit more space, but membership checks read like
if set[key] {
instead of if _, ok := set[key]; ok {
Re:PEP 584 – Add + and – operators to the built-in dict class
by zephyrfalcon on Wednesday March 06, 2019 @11:09AM
(#19319949)
Before Python grew a set type, it was common to implement them in a similar way, i.e. as a dict with some kind of default value (0, 1, None, etc).
Re:PEP 584 – Add + and – operators to the built-in dict class
by kevin_thibedeau on Wednesday March 06, 2019 @12:45PM
(#19320887)
Python sets are internally just a dict hash table for the keys with no associated values.
Re:PEP 584 – Add + and – operators to the built-in dict class
by sqd on Wednesday March 06, 2019 @11:52AM
(#19320361)
I think internally C++ STL set<T> is similarly just map<T, void>
Re:PEP 584 – Add + and – operators to the built-in dict class
by kbd on Wednesday March 06, 2019 @04:41AM
(#19317585)
> Interestingly enough some languages actually do the opposite.
Of course you can represent sets as dictionaries with empty values (ask anyone who programmed Perl). You're supporting my point that dicts logically subclass sets, because they can represent sets where the values can be other things as well.
You're also getting at what the behavior should be if you union a dictionary and a set. Hypothetical Python:
>>> s = {'a','b','c'}
>>> d = {'d': 'D'}
>>> d | s
>>> {'d': 'D', 'a': None, 'b': None, 'c': None}
Re:PEP 584 – Add + and – operators to the built-in dict class
by meatball-farmer on Wednesday March 06, 2019 @07:51AM
(#19318482)
I think he's flipping your point: sets are a subclass of dicts/maps, not vice-versa. Thinking of a maps as a set where it's value maps to something else sounds backwards because values in sets don't map to values arbitrarily (or at all in some cases); maps are maps.
Interestingly enough some languages actually do the opposite. In Rust for example a set is literally just a dictionary with unit as the value[0] and unit is essentially a way of expressing the absence of a value (it takes up no space in memory, and you just can't do anything with it).
[0]: https://doc.rust-lang.org/stable/src/std/collections/hash/se...
For posterity, the above link shows: