我想从函数而不是整个字典本身返回字典的引用。字典是全局声明的。
dict_1 = {
'1': "value 1",
'2': "value 2"
}
dict_2 = {
'1': "value 100",
'2': "value 200"
}
def get_relevant_dict(value):
if(value == 1):
return dict_1
elif(value == 2 or value == 3):
return dict_2
目前,当我调用get_relevant_dict
函数时,它会返回字典而不是引用。例如,
print(get_relevant_dict(1))
打印输出
{'1': "value 1",'2': "value 2"}
而不是位置。
如何让它返回参考?
答案 0 :(得分:4)
我猜你是基于其他语言(如C ++)在python上做出假设。
不知何故,在你的代码中,当你得到相同的对象时,你已经传递了#34;引用",指向相同的内存地址:
id(dict_1)
# 140246205511672
id((get_relevant_dict(1))
# 140246205511672
答案 1 :(得分:-1)
这是你从字典中返回密钥的方法:
dict_1.keys()