简体   繁体   English

在Python 2和3中统一生成字典的生成器

[英]Generators to iterate over a dictionary uniformly in both Python 2 and 3

Is there a way to efficiently iterate over the values/items in a dictionary that works in both Python 2 and Python 3? 有没有一种方法可以有效地迭代适用于Python 2和Python 3的字典中的值/项目?

In Python 2, I can write 在Python 2中,我可以编写

for x in mydict:
for x in mydict.iterkeys():
for x in mydict.viewkeys():
for x in mydict.itervalues():
for x in mydict.viewvalues():
for x in mydict.iteritems():
for x in mydict.viewitems():

and in Python 3, I have the following possibilities: 在Python 3中,我有以下几种可能性:

for x in mydict:
for x in mydict.keys():
for x in mydict.values():
for x in mydict.items():

So, I can iterate over the keys with for x in mydict , and that works in both Python 2 and 3. But is there a way to iterate over values and key-value pairs ('items') that works universally? 因此,我可以for x in mydict使用for x in mydict遍历键,该键在Python 2和3中都可以使用。但是是否有一种方法可以遍历通用的值和键值对(“项”)? I need it for writing Python code that can be run in both Python versions. 我需要它来编写可以在两个Python版本中运行的Python代码。

(On a side note, other obstacles with iterators can be bypassed easily; take for example: (附带说明,使用迭代器可以轻松绕过其他障碍;例如:

if sys.version_info.major<3:
    from itertools import izip as zip, imap as map

However, the dictionary methods cannot be redefined easily like map and zip .) 但是,字典方法不能像mapzip这样轻松地重新定义。)

Any ideas? 有任何想法吗?

values() version of Just another dunce's answer 另一个笨蛋的答案的values()版本

for value in (mydict[key] for key in mydict):

or 要么

def dict_values(d):
   return (mydict[key] for key in mydict)

def dict_items(d):
   return ((key, mydict[key]) for key in mydict)

for value in dict_values(mydict):
    ...

for value in dict_items(mydict):
    ...

This is pretty crappy though. 不过,这太糟糕了。 You could check the python version and instead of returning the generator, return d.items() or d.iteritems() as appropriate 您可以检查python版本,而不是返回生成器,而是根据需要返回d.items()d.iteritems()

I think a better question may be how to write Python2 code that works well with 2to3 and generates good Python3 code 我认为一个更好的问题可能是如何编写与2to3兼容并生成良好的Python3代码的Python2代码

The following code works in both Py2 and Py3: 以下代码适用于Py2和Py3:

def iteritems(d):
    'Factor-out Py2-to-3 differences in dictionary item iterator methods'
    try:
         return d.iteritems()
    except AttributeError:
         return d.items()

d = dict(red=1, blue=2, green=3)
for k, v in iteritems(d):
    print(k)
    print(v)
    print('')

Note, this solution has the advantage of using the native iterators rather than rolling your own generators and doing your own lookups. 请注意,此解决方案的优点是使用本机迭代器,而不是滚动自己的生成器并进行自己的查找。 The native iterators are faster than the other solutions presented. 本机迭代器比提供的其他解决方案更快。

This will give you a generator: 这将为您提供一个生成器:

for key,value in ((key,mydict[key] for key in mydict)

If you want a list, use [] around the expression instead of the () on the outside 如果需要列表,请在表达式周围使用[]而不是外部的()

Python2.7 has an .items method in the dictionary which allows you to iterate over (key,value) tuples. Python2.7在字典中有一个.items方法,它允许您遍历(键,值)元组。 Python3 has the same API (although the implementation is different). Python3具有相同的API(尽管实现不同)。 Will this work for you? 这对您有用吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM