我尝试了很多但是仍然有从函数返回字典的问题。我可以从函数内部打印d1和d2但不在外面打印。当我使用以下脚本时,我得到:NameError:name' d1'没有定义。谢谢您的帮助!
ref = """text a"""
target = """text b"""
def text_to_dict(x):
# value formatting to list = new_values
# key formatting to list = keys
# dict creation from keys and new_values
if x == ref:
d1 = dict(zip(keys, new_values))
return d1
elif x == target:
d2 = dict(zip(keys, new_values))
return d2
text_to_dict(ref)
text_to_dict(target)
print(d1)
print(d2)
答案 0 :(得分:1)
d1和d2是函数变量,它们在函数外部不可见。
dict1 = text_to_dict(ref)
dict2 = text_to_dict(target)
print(dict1)
print(dict2)