我有一个函数(items)返回一个dict(details_dict),并希望在另一个函数(内容)中打印出这个dict。
for循环之后的details_dict的内容是:
details_dict = {
'car' : 'fast',
'bike' : 'faster',
'train' : 'slow'
}
以下是我实施的两个功能,但我不确定它们是否正确。
def items(root):
for a in list: # example for loop, not important but details_dict is created here
details_dict = ['name' : 'state']
return details_dict
def contents(root):
for name, state in details_dict.items():
print ("%s is set to %s" % (name, state)
答案 0 :(得分:0)
您的打印声明中有一个缺少的括号和可能的缩进问题。这是您正在做的事情的修改版本,忽略了如何构建字典的详细信息:
def buildItems():
return {
'car': 'fast',
'bike': 'faster',
'train': 'slow'
}
def contents():
details_dict = buildItems()
for name, state in details_dict.items():
print ("%s is set to %s" % (name, state))
contents()
输出:
car is set to fast
train is set to slow
bike is set to faster
如果那是你想要它做的,那就有效。您可以从contents()函数内成功打印在另一个函数中创建的dict。
答案 1 :(得分:0)
在不知道数据结构的情况下,我做了最好的猜测。
list_a = ['car', 'bike', 'train']
list_b = ['fast', 'faster', 'slow']
def items (one, two):
the_dict = {}
for (i,j) in zip(one, two):
the_dict[i] = j
return the_dict
def contents(a_dict):
for key in a_dict:
print 'The key ' +key+ ' is assigned to '+a_dict[key]
details_dict = items(list_a, list_b)
contents(details_dict)
输出:
The key car is assigned to fast
The key train is assigned to slow
The key bike is assigned to faster