从函数迭代字典 [英] iterate dictionary from a function
本文介绍了从函数迭代字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
从函数迭代字典时遇到问题.
I'm having a problem iterating dictionary from a function.
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)
ValueError: too many values to unpack (expected 2)
推荐答案
您必须遍历 .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,4,'three':3,'two':2,'one':1}
.如果打印 dictionary.items()
,您将获得项目列表. [(''four',4),('three',3),('two',2),('one',1)]
.
If you print dictionary
you'll see that you get {'four': 4, 'three': 3, 'two': 2, 'one': 1}
. If you print dictionary.items()
you get the list of the items. [('four', 4), ('three', 3), ('two', 2), ('one', 1)]
.
这篇关于从函数迭代字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文