Randomly Named User Randomly Named User - 4 years ago 125
Python Question

Return dictionary reference from function in python2.7

I want to return the reference of a dictionary from a function instead of the entire dictionary itself. The dictionary is declared globally.

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


Currently, when I call the
get_relevant_dict
function, it returns the dictionary instead of the reference. For example,

print(get_relevant_dict(1))


prints an output

{'1': "value 1",'2': "value 2"}


instead of a location.

How do I get it to return the reference?

Answer Source

I guess you are making assumption on python based on other langages, like C++.

Somehow, in your code, you already are passing "references", as you get the same object, poiting to the same memory address :

id(dict_1)
# 140246205511672
id((get_relevant_dict(1))
# 140246205511672
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download