1. Abstract(摘要)

This PEP proposes(建议) to change the .keys(), .values() and .items() methods of the built-in dict type to return a set-like or unordered container object whose contents are derived from the underlying(潜在的) dictionary rather than a list which is a copy of the keys, etc.; and to remove the .iterkeys(), .itervalues() and .iteritems() methods.

The approach is inspired(灵感) by that taken in the Java Collections Framework [1].

2.Introduction

It has long been the plan to change the .keys(), .values() and .items() methods of the built-in dict type to return a more lightweight object than a list, and to get rid of .iterkeys(), .itervalues() and .iteritems(). The idea is that code that currently (in 2.x) reads:

for k, v in d.iteritems(): ...
should be rewritten as:

for k, v in d.items(): ...
(and similar for .itervalues() and .iterkeys(), except the latter is redundant since we can write that loop as for k in d.)

Code that currently reads:

a = d.keys() # assume we really want a list here
(etc.) should be rewritten as

a = list(d.keys())
There are (at least) two ways to accomplish(实现) this. The original plan was to simply let .keys(), .values() and .items() return an iterator, i.e. exactly what iterkeys(), itervalues() and iteritems() return in Python 2.x. However, the Java Collections Framework [1] suggests that a better solution is possible: the methods return objects with set behavior (for .keys() and .items()) or multiset (== bag) behavior (for .values()) that do not contain copies of the keys, values or items, but rather reference the underlying dict and pull their values out of the dict as needed.

The advantage(优势) of this approach is that one can still write code like this:

a = d.items()
for k, v in a: ...
# And later, again:
for k, v in a: ...
Effectively, iter(d.keys()) (etc.) in Python 3.0 will do what d.iterkeys() (etc.) does in Python 2.x; but in most contexts we don't have to write the iter() call because it is implied by a for-loop.

在python3.0中,iter(d.keys())等同于python2.0的d.iterkeys()  ,但是,在大多数场景下,我们不需要嗲用iter(),因为,可以使用简单的for循环实现。

list可迭代化,但不是迭代器。

https://stackoverflow.com/questions/45458631/how-python-built-in-function-iter-convert-a-python-list-to-an-iterator

The objects returned by the .keys() and .items() methods behave like sets. The object returned by the values() method behaves like a much simpler unordered collection -- it cannot be a set because duplicate values are possible.

Because of the set behavior, it will be possible to check whether two dicts have the same keys by simply testing:

if a.keys() == b.keys(): ...
and similarly for .items().

These operations are thread-safe only to the extent that using them in a thread-unsafe way may cause an exception but will not cause corruption of the internal representation.

As in Python 2.x, mutating a dict while iterating over it using an iterator has an undefined effect and will in most cases raise a RuntimeError exception. (This is similar to the guarantees made by the Java Collections Framework.)

The objects returned by .keys() and .items() are fully interoperable with instances of the built-in set and frozenset types; for example:

set(d.keys()) == d.keys()
is guaranteed to be True (except when d is being modified simultaneously by another thread).

Specification
I'm using pseudo-code to specify the semantics:

class dict:

# Omitting all other dict methods for brevity.
# The .iterkeys(), .itervalues() and .iteritems() methods
# will be removed.

def keys(self):
return d_keys(self)

def items(self):
return d_items(self)

def values(self):
return d_values(self)

class d_keys:

def __init__(self, d):
self.__d = d

def __len__(self):
return len(self.__d)

def __contains__(self, key):
return key in self.__d

def __iter__(self):
for key in self.__d:
yield key

# The following operations should be implemented to be
# compatible with sets; this can be done by exploiting
# the above primitive operations:
#
# <, <=, ==, !=, >=, > (returning a bool)
# &, |, ^, - (returning a new, real set object)
#
# as well as their method counterparts (.union(), etc.).
#
# To specify the semantics, we can specify x == y as:
#
# set(x) == set(y) if both x and y are d_keys instances
# set(x) == y if x is a d_keys instance
# x == set(y) if y is a d_keys instance
#
# and so on for all other operations.

class d_items:

def __init__(self, d):
self.__d = d

def __len__(self):
return len(self.__d)

def __contains__(self, (key, value)):
return key in self.__d and self.__d[key] == value

def __iter__(self):
for key in self.__d:
yield key, self.__d[key]

# As well as the set operations mentioned for d_keys above.
# However the specifications suggested there will not work if
# the values aren't hashable. Fortunately, the operations can
# still be implemented efficiently. For example, this is how
# intersection can be specified:

def __and__(self, other):
if isinstance(other, (set, frozenset, d_keys)):
result = set()
for item in other:
if item in self:
result.add(item)
return result
if not isinstance(other, d_items):
return NotImplemented
d = {}
if len(other) < len(self):
self, other = other, self
for item in self:
if item in other:
key, value = item
d[key] = value
return d.items()

# And here is equality:

def __eq__(self, other):
if isinstance(other, (set, frozenset, d_keys)):
if len(self) != len(other):
return False
for item in other:
if item not in self:
return False
return True
if not isinstance(other, d_items):
return NotImplemented
# XXX We could also just compare the underlying dicts...
if len(self) != len(other):
return False
for item in self:
if item not in other:
return False
return True

def __ne__(self, other):
# XXX Perhaps object.__ne__() should be defined this way.
result = self.__eq__(other)
if result is not NotImplemented:
result = not result
return result

class d_values:

def __init__(self, d):
self.__d = d

def __len__(self):
return len(self.__d)

def __contains__(self, value):
# This is slow, and it's what "x in y" uses as a fallback
# if __contains__ is not defined; but I'd rather make it
# explicit that it is supported.
for v in self:
if v == value:
return True
return False

def __iter__(self):
for key in self.__d:
yield self.__d[key]

def __eq__(self, other):
if not isinstance(other, d_values):
return NotImplemented
if len(self) != len(other):
return False
# XXX Sometimes this could be optimized, but these are the
# semantics: we can't depend on the values to be hashable
# or comparable.
olist = list(other)
for x in self:
try:
olist.remove(x)
except ValueError:
return False
assert olist == []
return True

def __ne__(self, other):
result = self.__eq__(other)
if result is not NotImplemented:
result = not result
return result

PEP 3106 -- Revamping(改进) dict.keys(), .values() and .items()的更多相关文章

  1. Python3基础 dict keys+values 循环打印字典中的所有键和值

             Python : 3.7.0          OS : Ubuntu 18.04.1 LTS         IDE : PyCharm 2018.2.4       Conda ...

  2. 查询set、dict、dict.keys()的速度对比

    查找效率:set>dict>list 单次查询中: list set dict O(n) set做了去重,本质应该一颗红黑树 (猜测,STL就是红黑树),复杂度 O(logn): dict ...

  3. ES2017 keys,values,entries使用

    let {keys, values, entries} = Object; let obj = { a: 1, b: 2, c: 3 }; for (let key of keys(obj)) { c ...

  4. StackExchange.Redis 官方文档(五) Keys, Values and Channels

    原文:StackExchange.Redis 官方文档(五) Keys, Values and Channels Keys, Values and Channels 在使用redis的过程中,要注意到 ...

  5. 37-python基础-python3-字典的常用方法-keys()-values()-items()

    有 3 个字典方法,它们将返回类似列表的值,分别对应于字典的键.值和键-值对:keys().values()和 items(). 这些方法返回的值不是真正的列表,它们不能被修改,没有append()方 ...

  6. ES6扩展——数组的新方法(Array.from、Array.of、Array.fill、Array.includes、keys values entries 、find)

    1.Array.from(objec,回调函数)将一个ArrayLike对象或者Iterable对象(类数组对象)转换成一个数组 1)该类数组对象必须具有length属性,用于指定数组的长度.如果没有 ...

  7. fromkeys() keys() values() items()

    fromkeys() >>> dict1={} >>> dict1.fromkeys((1,2,3))#会自动为没有赋值的值建立none {1: None, 2: ...

  8. keys(),values()和items()

    a={'a':11,'b':'bb','c':321}for x in a.items(): print(x)  # 每条都输出来print("------------")for ...

  9. python中的keys、values、items

    keys()获取字典中所有的键并放入列表 values()获取字典中所有的值并放入列表 items()获取字典中所有的键值对并放入列表 举个例子: 1 a = { 2 "name" ...

随机推荐

  1. 软件工程项目组Z.XML会议记录 2013/11/06

    软件工程项目组Z.XML会议记录 [例会时间]2013年11月06日星期二21:00-22:00 [例会形式]小组讨论 [例会地点]三号公寓楼会客厅 [例会主持]李孟 [会议记录]薛亚杰 会议整体流程 ...

  2. java多线程二之线程同步的三种方法

          java多线程的难点是在:处理多个线程同步与并发运行时线程间的通信问题.java在处理线程同步时,常用方法有: 1.synchronized关键字. 2.Lock显示加锁. 3.信号量Se ...

  3. Liz问题账户分析系统

    1.理解liz工作情况,了解liz的问题,具有同理心.设想软件应该达成的目标,解决哪些业务. 第一步:就是从系统角度来理解软件,确定对所开发系统的综合要求,并提出这些需求的实现条件,以及需求应该达到的 ...

  4. 【Python】Python中子类怎样调用父类方法

    python中类的初始化方法是__init__(),因此父类子类的初始化方法都是这个,如果子类不实现这个函数,初始化时调用父类的初始化函数,如果子类实现这个函数,就覆盖了父类的这个函数,既然继承父类, ...

  5. Impala-1

    Impala相关操作上   阅读目录 序 数据库相关 表相关 系列索引 序 上一篇,我们介绍Impala的介绍及安装.   下面我们开始继续进一步的了解Impala的相关操作. 数据库相关 一:创建 ...

  6. 【bzoj2733】[HNOI2012]永无乡 Treap启发式合并

    题目描述 永无乡包含 n 座岛,编号从 1 到 n,每座岛都有自己的独一无二的重要度,按照重要度可 以将这 n 座岛排名,名次用 1 到 n 来表示.某些岛之间由巨大的桥连接,通过桥可以从一个岛 到达 ...

  7. [洛谷P3919]【模板】可持久化数组

    题目大意:有两个操作,1:在第x次操作后的版本上修改一个值,2:查询在第x次操作后的版本上的一个节点的值 即: 你需要维护这样的一个长度为N的数组,支持如下几种操作 1.在某个历史版本上修改某一个位置 ...

  8. [Leetcode] Anagrams 颠倒字母构成词

    Given an array of strings, return all groups of strings that are anagrams. Note: All inputs will be ...

  9. 安徽师大附中%你赛day4T2 演讲解题报告

    演讲 题目背景: 众所周知,\(\mathrm{Zdrcl}\)是一名天天\(\mathrm{AK}\)的高水平选手. 作为一民长者,为了向大家讲述自己\(\mathrm{AK}\)的经验,他决定在一 ...

  10. BZOJ 3262: 陌上花开 CDQ

    这个题大部分人用了离散然后水之,然而.....作为一只蒟蒻我并没有想到离散,而是直接拿两个区间一个对应n,一个对应k来搞,当然这两个区间是对应的,我把第一维排序,第二维CDQ,第三维树状数组,然而由于 ...