-2

I have the following code:

def all_dsc(x):
    dict={'a':x+2,'b':x-2}
    return dict

I would like to to call keys from specifically this dictionary outside of the function. smthn like:

all_dsc.dict.keys()

What's the best way of doing it?

Mario L
  • 507
  • 1
  • 6
  • 15
  • Possible duplicate of [Access a function variable outside the function in Python without using \`global\`](http://stackoverflow.com/questions/19326004/access-a-function-variable-outside-the-function-in-python-without-using-global) – Lav Jan 12 '16 at 12:03
  • @Lav: that's not actually all that helpful a duplicate. Setting an attribute on the function is no different from setting a global; all you did is namespace it, but many issues with globals still apply (it is not thread-safe, for example). – Martijn Pieters Jan 12 '16 at 12:07

1 Answers1

2

You can't access locals in a function from outside the function. All you can do is return the dictionary object by calling the function, which you already do.

Call the function, and then just treat the result of the call expression as a dictionary:

all_dsc(42).keys()

Demo:

>>> all_dsc(42)
{'a': 44, 'b': 40}
>>> all_dsc(42).keys()
['a', 'b']

Note that you really shouldn't use the name of a built-in type as a variable if you can avoid it. dict is a built-in type, so try to use a different name here:

def all_dsc(x):
    mapping = {'a': x + 2, 'b': x - 2}
    return mapping

or even avoid creating a local at all, since it doesn't matter here:

def all_dsc(x):
    return {'a': x + 2, 'b': x - 2}
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • thanks a lot, didnt know that I have to pass an argument to the function to call the keys. – Mario L Jan 12 '16 at 12:01
  • another question: what if i have multiple dictionaries in a function? how do i call the keys from each of them? – Mario L Jan 12 '16 at 12:04
  • @MarioL: return them all in a tuple: `return d1, d2, d3`, then index the tuple or use tuple unpacking to store the dictionaries in separate variables first. – Martijn Pieters Jan 12 '16 at 12:05