【问题标题】:iterate dictionary from a function从函数中迭代字典
【发布时间】:2015-10-30 09:59:06
【问题描述】:

我在从函数中迭代字典时遇到问题。

def iteratedic():
    datadic={
    "one" : 1,
    "two" : 2,
    "three" : 3,
    "four" : 4
    }

    return datadic

def getdic():
    dictionary = iteratedic()
    for m, n in dictionary:
        print (m, n)

getdic()

上面写着

ValueError:解包的值太多(预计 2 个)

【问题讨论】:

  • 使用dictionary.items()
  • for m, n in dictionary.items():

标签: python function dictionary


【解决方案1】:

你必须遍历.items()

def iteratedic():
    datadic={
    "one" : 1,
    "two" : 2,
    "three" : 3,
    "four" : 4
    }

    return datadic

def getdic():
    dictionary = iteratedic()
    for m, n in dictionary.items():
        print (m, n)

getdic()

如果你打印 dictionary 你会看到你得到 {'four': 4, 'three': 3, 'two': 2, 'one': 1} 。如果您打印dictionary.items(),您将获得项目列表。 [('four', 4), ('three', 3), ('two', 2), ('one', 1)].

【讨论】:

  • 使用生成器会更好。 iteritems()呢?
【解决方案2】:

如果我们做for i in my_dict,那么它会给出keys,而不是keys: values。示例:

>>> a = {"one" : 1, "two" : 2, "three" : 3, "four" : 4}
>>> for i in a:
...     print(i)
... 
four
three
two
one

因此,如果您执行for i, j in my_dict,则会引发错误。

您可以使用dict.items(),它返回一个列表,将所有键和值保存在元组中,如下所示:

>>> a.items()
[('four', 4), ('three', 3), ('two', 2), ('one', 1)]

所以你可以这样做......

def getdic():
    dictionary = iteratedic()
    for m, n in dictionary.items():
        print (m, n)

另外,dict.iteritems()dict.items() 更好,它返回一个生成器(但请注意,在 Python 3.x 中,dict.iterms() 返回一个生成器并且没有 dict.iteritems())。

另见:What is the difference between dict.items() and dict.iteritems()?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-22
    • 1970-01-01
    • 2013-02-01
    • 1970-01-01
    • 2018-09-04
    • 2014-09-12
    • 1970-01-01
    • 2020-01-17
    相关资源
    最近更新 更多