Get key, value inside class | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Get key, value inside class

What is the best way to get a key or a value of a dictionary inside a function of a class!? example: class Test: def test_func(self): my_dict = { 'a': 1, 'b': 2, } The best way to get the keys or values?

20th May 2019, 10:05 PM
Dolan
Dolan - avatar
7 Answers
+ 4
Thank you Eduardo Petry for your point about making more than one object and its disadvantages!
21st May 2019, 9:33 AM
Dolan
Dolan - avatar
+ 3
Dolan Hêriş There is a disadvantage of doing it that way. Each time you call Test() you are actually creating an object of the Test class and then the garbage collector immediately destroys it. So you are essentially creating 3 objects. The way I did, I created just one object that can be used indefinitely as long as the program runs. (Even though I used it only once)
20th May 2019, 10:29 PM
Eduardo Petry
Eduardo Petry - avatar
+ 3
~ swim ~ no mind my friend, thanks for your help
20th May 2019, 10:31 PM
Dolan
Dolan - avatar
+ 2
You need to return the dictonary to be able to manipulate it from outside the function/class. class Test: def test_func(self): my_dict = { 'a': 1, 'b': 2, } return my_dict test_object = Test() dict_outside_class = test_object.test_func() for key, value in dict_outside_class.items(): print(key, value)
20th May 2019, 10:15 PM
Eduardo Petry
Eduardo Petry - avatar
+ 2
@~ swim ~ I think your way is not working for getting them inside a function of a class!
20th May 2019, 10:21 PM
Dolan
Dolan - avatar
+ 2
Wow, have learnt from you guys. consider this: how would you work with list in dictionary. when two of the keys have list and these list. are integers.eg Phy= [] students = {"name":"ken","test":[2,6,6,9],"practicals":[10,13 ,19,24,20],"exam":47" "name":harry":"test":[6,9 7,7],"practicals":[19 25,22,27,27],"exam":38, is it possible to print out the sum of the test value divide by 2 while that of the practical side by 3.
23rd May 2019, 9:11 PM
Femi SONI Y
Femi SONI Y - avatar
+ 1
Eduardo Petry or a clearer way to me: class Test: def test_func(self): my_dict = { 'a': 1, 'b': 2, } return my_dict for key, value in Test().test_func().items(): print(key, value) for key in Test().test_func().keys(): print(key) for value in Test().test_func().values(): print(value)
20th May 2019, 10:26 PM
Dolan
Dolan - avatar