-1

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?

Randomly Named User
  • 1,889
  • 7
  • 27
  • 47
  • What do you mean by "location"? Memory address? – DainDwarf Dec 31 '15 at 11:10
  • 1
    you are not in C/C++/Java : What you get is the global object. If you change data of this return data, you change data of the global dict_? . So, don't really understand what you want exactly, and why. – A.H Dec 31 '15 at 11:11
  • 3
    `return dict_1` already returns the Python equivalent of what a "reference" is in C++. That is, no data is being copied. But actually Python is neither call-by-value nor call-by-reference. For more, see http://stackoverflow.com/questions/10262920/understanding-pythons-call-by-object-style-of-passing-function-arguments – Claudiu Dec 31 '15 at 11:13
  • Also see [Facts and myths about Python names and values](http://nedbatchelder.com/text/names.html) by SO veteran Ned Batchelder. – PM 2Ring Dec 31 '15 at 11:17

2 Answers2

4

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, pointing to the same memory address :

id(dict_1)
# 140246205511672
id((get_relevant_dict(1))
# 140246205511672
DainDwarf
  • 1,651
  • 10
  • 19
-1

This is how you return the keys off a dictionary:

dict_1.keys()
Tristan
  • 2,000
  • 17
  • 32