Python 3: dict & dict.keys()

Steven D'Aprano steve+comp.lang.python at pearwood.info
Thu Jul 25 01:48:36 EDT 2013


On Wed, 24 Jul 2013 08:57:11 -0700, Ethan Furman wrote:

> My point is that in 2.x .keys() did something different from the dict,
> while in 3.x it appears to me that they are the same.

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}


Dicts aren't sets, and don't support set methods:

py> d1 - d2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'dict' and 'dict'


> Peter's point is that in the stdlib the new functionality of .keys() is
> never used, not even once.

The standard library is not the universe of Python code, and most of the 
standard library predates Python 3. Some of it goes back to Python 1 
idioms. In general, working code doesn't get updated until it stops 
working.

I have code that manually walks over each dict and extracts keys that are 
in both, or one but not the other. Once I drop support for Python 2.6, I 
throw that code away and just use views. But until then, I'm stuck doing 
it the horrible way. Judging by a naive grep of my code, you might think 
I never used views. I do, I just have to reinvent the wheel.



-- 
Steven



More information about the Python-list mailing list