python迭代dict列表

2024-10-02 18:25:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字典列表,我正在反复阅读。我希望能够将列表传递给一个容器对象,然后在遍历容器时检索每个dict值的元组。在

例如:

myDict = {"key1": "value1string", "key2": "value2string"}
myList = [myDict]

container = ContainerObj(myList)
for value1, value2 in container:
    print "value1 = %s, value2 = %s" % value1, value2

我希望输出是:

^{pr2}$

我如何在ContainerObj中定义__iter__方法来实现这一点?在

我试着做了以下没用的事:

class ContainerObj(object):
    def __init__(self, listArg):
        self.myList = listArg
        self.current = 0
        self.high = len(self.myList)

    def __iter__(self):
        return self.myList.__iter__()

    def __next__(self):
        if self.current >= self.high:
            raise StopIteration
        else:
            myDict = self.myList[self.current]
            self.current += 1
            return (
                    myDict.get("key1"),
                    myDict.get("key2")
            )

Tags: self列表containerdefcurrent容器mydictkey2
2条回答

要获得所需的输出,只需执行以下操作。在

t={'l':'t','t':'l'}

','.join('{}={}'.format(key, val) for key, val in t.items())

output = 'l=t,t=l'

我想你想要的是generators。通常通过在函数中使用yield而不是return来实现这一点。但在您的情况下,我认为您可以使用itertools来帮助:

from itertools import chain
item_gen = chain(d.values() for d in my_dicts_list)
# Edit: Note that this will give you values continuously (not what you want), should have done
# item_gen = (d.values() for d in my_dicts_list)

要在类中执行此操作,可以执行以下操作:

^{pr2}$

然后可以像使用任何iterable一样使用此对象:

my_con = MyContainer([{"a": 1, "b": 2}, {"a": 3, "b": 4}])
for val1, val2 in my_con:
    print "a = %s; b = %s" % (val1, val2)

编辑1:哎哟,我意识到我在退货。你只想要价值观。在

而且,你基本上是自己制造发电机。使用内置的功能,它将更容易和更少的痛苦。我强烈建议您看看itertools模块。还有字典的iterkeysitervalues、和{}方法。在

相关问题 更多 >