سؤال

where can one find information on methods of dictionaries that are most forward/backwards compatible? for example, things that are unchanged between python 2.5 onward and are also going to be supported in python3?

for example: I am not sure if d.itervalues() is a backward/forward compatible method to use? I use it to get a single element from a dictionary:

# is this good form for those who care about compatibility?
d = {"foo": {"bar": []}}
elt = next(d.itervalues())

لا يوجد حل صحيح

نصائح أخرى

For this specific method dictionary.itervalues(), it changed to dictionary.values() in Python 3.

Check this library that addresses the compatibility issues between Python 2 &3

https://pythonhosted.org/six/

It would be forward compatible to use .values() if that is unlikely to be a very large list when materialized in memory.

To be certain, you can do this:

d = {"foo": {"bar": []}}
elt = next(iter(d.values()))

and elt returns

{'bar': []}

I personally tested that this works in Python 2.6 & 3.3, but iter was first available in 2.2.

The code would be forward compatible, and then you could clean up the iter parts when you no longer wish for support in 2.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top