Movatterモバイル変換


[0]ホーム

URL:


Following system colour schemeSelected dark colour schemeSelected light colour scheme

Python Enhancement Proposals

PEP 274 – Dict Comprehensions

Author:
Barry Warsaw <barry at python.org>
Status:
Final
Type:
Standards Track
Created:
25-Oct-2001
Python-Version:
2.7, 3.0
Post-History:
29-Oct-2001

Table of Contents

Abstract

PEP 202 introduces a syntactical extension to Python called the“list comprehension”. This PEP proposes a similar syntacticalextension called the “dictionary comprehension” or “dictcomprehension” for short. You can use dict comprehensions in waysvery similar to list comprehensions, except that they producePython dictionary objects instead of list objects.

Resolution

This PEP was originally written for inclusion in Python 2.3. Itwas withdrawn after observation that substantially all of itsbenefits were subsumed by generator expressions coupled with thedict() constructor.

However, Python 2.7 and 3.0 introduces this exact feature, as wellas the closely related set comprehensions. On 2012-04-09, the PEPwas changed to reflect this reality by updating its Status toAccepted, and updating the Python-Version field. The OpenQuestions section was also removed since these have been longresolved by the current implementation.

Proposed Solution

Dict comprehensions are just like list comprehensions, except thatyou group the expression using curly braces instead of squarebraces. Also, the left part before thefor keyword expressesboth a key and a value, separated by a colon. The notation isspecifically designed to remind you of list comprehensions asapplied to dictionaries.

Rationale

There are times when you have some data arranged as a sequences oflength-2 sequences, and you want to turn that into a dictionary.In Python 2.2, thedict() constructor accepts an argument that isa sequence of length-2 sequences, used as (key, value) pairs toinitialize a new dictionary object.

However, the act of turning some data into a sequence of length-2sequences can be inconvenient or inefficient from a memory orperformance standpoint. Also, for some common operations, such asturning a list of things into a set of things for quick duplicateremoval or set inclusion tests, a better syntax can help codeclarity.

As with list comprehensions, an explicit for loop can always beused (and in fact was the only way to do it in earlier versions ofPython). But as with list comprehensions, dict comprehensions canprovide a more syntactically succinct idiom that the traditionalfor loop.

Semantics

The semantics of dict comprehensions can actually be demonstratedin stock Python 2.2, by passing a list comprehension to thebuilt-in dictionary constructor:

>>>dict([(i,chr(65+i))foriinrange(4)])

is semantically equivalent to:

>>>{i:chr(65+i)foriinrange(4)}

The dictionary constructor approach has two distinct disadvantagesfrom the proposed syntax though. First, it isn’t as legible as adict comprehension. Second, it forces the programmer to create anin-core list object first, which could be expensive.

Examples

>>>print{i:chr(65+i)foriinrange(4)}{0 : 'A', 1 : 'B', 2 : 'C', 3 : 'D'}
>>>print{k:vfork,vinsomeDict.iteritems()}==someDict.copy()1
>>>print{x.lower():1forxinlist_of_email_addrs}{'barry@zope.com'   : 1, 'barry@python.org' : 1, 'guido@python.org' : 1}
>>>definvert(d):...return{v:kfork,vind.iteritems()}...>>>d={0:'A',1:'B',2:'C',3:'D'}>>>printinvert(d){'A' : 0, 'B' : 1, 'C' : 2, 'D' : 3}
>>>{(k,v):k+vforkinrange(4)forvinrange(4)}...{(3,3):6,(3,2):5,(3,1):4,(0,1):1,(2,1):3,   (0, 2): 2, (3, 0): 3, (0, 3): 3, (1, 1): 2, (1, 0): 1,   (0, 0): 0, (1, 2): 3, (2, 0): 2, (1, 3): 4, (2, 2): 4, (   2, 3): 5}

Implementation

All implementation details were resolved in the Python 2.7 and 3.0time-frame.

Copyright

This document has been placed in the public domain.


Source:https://github.com/python/peps/blob/main/peps/pep-0274.rst

Last modified:2025-02-01 08:59:27 GMT


[8]ページ先頭

©2009-2025 Movatter.jp