Reputation: 1541
I'm trying to use an OrderedDict in Jython. When I write it in Python, it works fine; however, when I try the same code with Jython, it gives a Java error (I have also had it say that the collections module has no attribute OrderedDict). The module error was as follows:
ERROR: Exception (main): 'module' object has no attribute 'OrderedDict'
So what I'm trying to do is output the values of the dictionary in the same order that they were put in. I want to create the following functionality (written in Python) in Jython:
import collections
example = collections.OrderedDict()
example["c"] = 3
example["b"] = 4
example["d"] = 3
example["e"] = 9
example["a"] = 7
for key, value in example.iteritems():
print key + ": " + str(value)
This would result in:
c: 3
b: 4
d: 3
e: 9
a: 7
Now I am ASSUMING that the reason this is not working for me in Jython is because OrderedDict does not exist in it. With that being said, is there a way to do this in Jython? Maybe it requires Java code?
EDIT:
I figured out a way to do it using a list and tuples, like so:
example = []
example.append(("c", 3))
example.append(("b", 4))
example.append(("d", 3))
example.append(("e", 9))
example.append(("a", 7))
for tup in example:
key, value = tup
print key + ": " + str(value)
While this works, I'd still like to know how to do it with a dictionary.
Upvotes: 1
Views: 870
Reputation: 1953
If you need collections.OrderedDict
, you must use Jython version 2.7 or later, because collections.OrderedDict
was not introduced into Python until version 2.7.
Upvotes: 3