-1

In the following code block i want to transmit just the name of a dictionary (result_dict) but not the content.

def define_var(dictionary, entry, counter):
  for i in range(counter):
    print "reason%d = %s['%s_%d']" % (i + 1, dictionary, entry, counter)

when i call the function like:

define_var(result_dict, 'start', 3)

it prints:

reason1 = {'start_2': 'test2', 'start_3': 'test3', 'start_1': 'test1'}['start_1']

but i want to print it like that:

reason1 = result_dict[start_1]

reason2 = result_dict[start_2]

and so on

Alex Held
  • 123
  • 11
  • 1
    The idea of the "name" of the dictionary makes no sense for Python. – Ffisegydd Feb 09 '15 at 10:01
  • 1
    From your code there is no way for the function to magically know that you think your dictionary is called `result_dict`, unless you pass in the string `"result_dict"`. – khelwood Feb 09 '15 at 10:03
  • when i call the function i write result_dict as first parameter. but it prints me the content of result_dict instead of 'result_dict' – Alex Held Feb 09 '15 at 10:04
  • do you have more than one dict defined? – Padraic Cunningham Feb 09 '15 at 10:14
  • yea. got many dicts. – Alex Held Feb 09 '15 at 10:21
  • The "name" of a variable (e.g. dictionary) is not an intricate part of the variable. Instead, it is a tag, floating in the namescope of the code that points to the variable. When you write ``define_var(result_dict)`` the function receives a pointer to the variable. In this sense, the "name" of the dictionary has no meaning to Python. – MrGumble Feb 09 '15 at 12:32

1 Answers1

0

You can find the object in globals:

def define_var(dictionary, entry, counter):
    d_name = next(k for k, v in globals().items() if v  is  dictionary)
    for i in range(counter):
        print("reason%d = %s['%s_%d']" % (i + 1, d_name, entry, counter))

print(define_var(result_dict, 'start', 3))


reason1 = result_dict['start_3']
reason2 = result_dict['start_3']
reason3 = result_dict['start_3']  

If you print(id(result_dict)) and print(id(dictionary)) in the function when you pass in result_dict you will see they both are the same object with the same id's so we just use is to get the name from the global dict.

If you want to assign the result to a reason variable you can return it, something like:

def define_var(dictionary, entry, counter):
    d_name = next(k for k, v in globals().items() if v is dictionary)
    return "%s['%s_%d']" % (d_name, entry, counter)

reason  = define_var(result_dict,2,3)
print(reason)

Or use a dict:

def define_var(dictionary, entry, counter):
    d_name = next(k for k, v in globals().items() if v  is  dictionary)
    reasons = {}
    for i in range(counter):
        reasons["reason{}".format(i)] = "{}[{}]".format(d_name, entry)
    return reasons
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321