+ 2
How to get dict keys inside a function!?
How to get dict keys, or values inside a function!? https://code.sololearn.com/cFTlS2sb5X1e/?ref=app
15 odpowiedzi
+ 4
hi i found a way for it in this article
https://www.codesdope.com/blog/article/nested-function-scope-of-variable-closures-in-pyth/
+ 4
Dolan Hêriş it depends. if you rlly need to return the value, then return it. otherwise using global
+ 3
Use the dictionary.keys() method
def test():
x = {
1: "a",
2: "b",
3: "c"
}
print(x.keys())
test()
+ 3
that's also right . bUt if u dont want to return a value, then you have to declare the dict in the global scope and do this trick.
ex:
x = {}
def test():
global x
x = {1:4,5:10}
test()
print(x) #dict assigned in function
+ 2
Still you can do it
#getting 1st element
print(list(x.keys())[0])
#prints all keys individually
for i in x.keys():
print(i)
+ 2
You mean accessing function scope variables from outside
+ 2
Closures, what Seniru Pasan linked.
def f(dictionary):
def g(key):
while True:
return dictionary[key]
return g
my_dict = f({'a': 1, 'b': 2})
print(my_dict('b'))
You create my_dict with a dictionary that it will remember; then you can access the values by handing over the keys.
+ 2
If you define your dictionary inside a normal function, it will be created and deleted every time you call the function.
With a closure, you create the dict only once and keep it for later calls.
Global is only necessary if you want to reassign the name; you don't even have to pass an item but can read it from inside the function anyway. And if it's mutable, you can even change it.
And you don't have to worry about passing args or returning stuff, because it's only a reference anyway.
+ 2
Dolan Hêriş, further up I have written how you can build the closure. Do you mean that? Or do you need an example for something else?
+ 1
I think this way won’t be useful to access values or keys to use them outside the function. it will only prints them. let’s say I want to use only one key or one value, then this way won’t be helpful, right??
+ 1
HonFu can you give an example to make it more clear, please?
0
Seniru Pasan
I want the same thing but not inside the function.
I want to access it outside of the function.
0
Yes.
I have the dictionary in a function.
I want to get the keys an values from outside then I can use only what I call not all of them by printing the function.
0
do you think it is correct?
https://code.sololearn.com/cFTlS2sb5X1e/?ref=app
0
Thanks. With global, it is also works fine. which one is better? does returning couse any issue inside the function!? what about global!?