Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!feeder.erje.net!eu.feeder.erje.net!newsfeed.fsmpi.rwth-aachen.de!news-1.dfn.de!news.dfn.de!fu-berlin.de!uni-berlin.de!individual.net!not-for-mail From: Neil Cerutti Newsgroups: comp.lang.python Subject: Re: Python 3: dict & dict.keys() Date: 24 Jul 2013 12:54:36 GMT Organization: Norwich University Lines: 48 Message-ID: References: <51EF2AD8.3080105@stoneleaf.us> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit X-Trace: individual.net fnOFG5oSocQso1WJtbdt1gFjVoYhcu8Vs6/8lXzJCpRtoPvXQL Cancel-Lock: sha1:3VSjbbcH/6QPlrUIkSmunPODFsw= User-Agent: slrn/0.9.9p1/mm/ao (Win32) Xref: csiph.com comp.lang.python:51128 On 2013-07-24, Peter Otten <__peter__@web.de> wrote: >> So, my question boils down to: in Python 3 how is dict.keys() >> different from dict? What are the use cases? > > I just grepped through /usr/lib/python3, and could not identify > a single line where some_object.keys() wasn't either wrapped in > a list (or set, sorted, max) call, or iterated over. > > To me it looks like views are a solution waiting for a problem. Here's a case of using keys as a set-like view from my own "production" code (i.e., I used it once for one important job): seen = set() students = {} dates = [] for fname in sorted(glob.glob("currentterm201320?.csv")): print(fname, end="\n\t") date = get_date(fname) dates.append(date) term = fname[-11:-4] r = reg.registration(term, path=".") regs = r.keys() for alt_id in regs & seen: students[alt_id].append(r[alt_id]) for alt_id in seen - regs: students[alt_id].append(None) for alt_id in regs - seen: students[alt_id] = [None]*(len(dates)-1) + [r[alt_id]] seen.add(alt_id) It was a very nice way to to do three different things depending on the student sin the set I was working with, compared to a registration list: Granted the line was originally "regs = set(regs.keys())" before it occurred to me that it sucked to take what must be equivalent to a set, convert to a list, and then back to set again. Thanks to the set-like view of dict.keys it worked just like one might hope. Looking at it again "seen" might be a redundant parallel version of students.keys(). -- Neil Cerutti