【发布时间】:2015-02-10 17:26:43
【问题描述】:
我正在尝试在 Jython 中使用 OrderedDict。当我用 Python 编写它时,它工作正常;但是,当我使用 Jython 尝试相同的代码时,它会给出一个 Java 错误(我也说过集合模块没有属性 OrderedDict)。模块错误如下:
ERROR: Exception (main): 'module' object has no attribute 'OrderedDict'
所以我要做的是按照输入的顺序输出字典的值。我想在 Jython 中创建以下功能(用 Python 编写):
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)
这将导致:
c: 3
b: 4
d: 3
e: 9
a: 7
现在我假设这在 Jython 中对我不起作用的原因是因为其中不存在 OrderedDict。话虽如此,有没有办法在 Jython 中做到这一点?也许它需要 Java 代码?
编辑:
我想出了一种使用列表和元组的方法,如下所示:
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)
虽然这行得通,但我仍然想知道如何使用字典。
【问题讨论】:
-
您的问题应该包括您看到的错误。我猜你看到的是这样的:
AttributeError: 'module' object has no attribute 'OrderedDict' -
正确,抱歉 - 已添加
标签: python iteration jython ordereddictionary