Python 3: dict & dict.keys()

Johannes Bauer dfnsonfsduifb at gmx.de
Thu Jul 25 09:22:59 EDT 2013


On 25.07.2013 07:48, Steven D'Aprano wrote:

> Then you aren't looking very closely. d.keys() returns a set-like view 
> into the dict, which is great for comparing elements:
> 
> py> d1 = dict.fromkeys([1, 2, 3, 4])
> py> d2 = dict.fromkeys([3, 4, 5, 6])
> py> d1.keys() & d2.keys()  # keys that are in both
> {3, 4}
> py> d1.keys() ^ d2.keys()  # keys not in both
> {1, 2, 5, 6}
> py> d1.keys() - d2.keys()  # keys only in d1
> {1, 2}
> py> d2.keys() - d1.keys()  # keys only in d2
> {5, 6}

I know this is completely off-topic, but I really must thank you for
showing that neat trick. I didn't know set()'s operators &, ^, - were
overloaded (and always used difference/intersection, etc). That's
really, really neat.

Thanks again,
Joe

-- 
>> Wo hattest Du das Beben nochmal GENAU vorhergesagt?
> Zumindest nicht öffentlich!
Ah, der neueste und bis heute genialste Streich unsere großen
Kosmologen: Die Geheim-Vorhersage.
 - Karl Kaos über Rüdiger Thomas in dsa <hidbv3$om2$1 at speranza.aioe.org>



More information about the Python-list mailing list