0

I can't figure out how to print the whole output out of a loop from tested Kivy Minimal Reproducible Example below:

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout


class DataTable(BoxLayout):
    def __init__(self,table='', **kwargs):
        super().__init__(**kwargs)

        def build(self):

            datas = {}
            for i in range(3):
                data = {
                    '1':{i:'TESTa'},
                    '2':{i:'TESTb'},
                    '3':{i:'TESTc'},
                } #data store

                datas.update(data)

            print(datas)


        test = build(self)

class DataTableApp(App):
    def build(self):
        return DataTable()

if __name__=='__main__':
    DataTableApp().run()

It outputs the last dictionary item only as:

{'1': {2: 'TESTa'}, '2': {2: 'TESTb'}, '3': {2: 'TESTc'}}

While with the

print(datas)

as this

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout


class DataTable(BoxLayout):
    def __init__(self,table='', **kwargs):
        super().__init__(**kwargs)

        def build(self):

            datas = {}
            for i in range(3):
                data = {
                    '1':{i:'TESTa'},
                    '2':{i:'TESTb'},
                    '3':{i:'TESTc'},
                } #data store

                datas.update(data)

                print(datas)


        test = build(self)

class DataTableApp(App):
    def build(self):
        return DataTable()

if __name__=='__main__':
    DataTableApp().run()

inside the for loop scope it does print the whole dictionary as:

{'1': {0: 'TESTa'}, '2': {0: 'TESTb'}, '3': {0: 'TESTc'}}
{'1': {1: 'TESTa'}, '2': {1: 'TESTb'}, '3': {1: 'TESTc'}}
{'1': {2: 'TESTa'}, '2': {2: 'TESTb'}, '3': {2: 'TESTc'}}

I tried as per those answers (initializing the empty dictionary variable datas = {} outside and above the for loop scope) :

https://stackoverflow.com/a/65779535/10789707

https://stackoverflow.com/a/66901779/10789707

https://stackoverflow.com/a/61539025/10789707

https://stackoverflow.com/a/56638281/10789707

I was Expecting the 2nd output above when the print statement print(datas) is outside the loop scope:

{'1': {0: 'TESTa'}, '2': {0: 'TESTb'}, '3': {0: 'TESTc'}}
{'1': {1: 'TESTa'}, '2': {1: 'TESTb'}, '3': {1: 'TESTc'}}
{'1': {2: 'TESTa'}, '2': {2: 'TESTb'}, '3': {2: 'TESTc'}}

The end use would be to then use the whole dictionary (not just the last key value pair pair) to display in the Kivy window app as per the source example from github script:

https://github.com/mfazrinizar/Datatable-Kivy/blob/master/datatable.py

The data dictionary keys values pairs must all be accessible outside of the loop in order to then display them in the Kivy window.

Here's other documentation and resources I've consulted:

https://towardsdatascience.com/3-ways-to-iterate-over-python-dictionaries-using-for-loops-14e789992ce5

https://realpython.com/iterate-through-dictionary-python/

for loop printing out last item in my array only

https://qr.ae/pv0JvZ

Why does declaring the variable outside the for loop print all the elements of an array but declaring first inside the for loop prints only the last?

Why python only printing the last key from dictionary?

Append a dictionary to a dictionary

https://www.youtube.com/watch?v=nCdcFOLww_c

https://www.geeksforgeeks.org/iterate-over-a-dictionary-in-python/

Python dictionary only keeps information from last iteration of loop

Lod
  • 657
  • 1
  • 9
  • 30

1 Answers1

0

From the documentation: the update method overwrites the values for the keys.

To keep things simple, consider only what happens to the key '1'.

On the first iteration the value is set to {0: 'TESTa'}. On the second iteration the value is set to {1: 'TESTa'}. Remember, the method overwrites the values it doesn't "update" the values.

If you want to update the values, you will need to do something like the following.

datas['1'].update({i: 'TESTa'})

Edit based on comments

I'm not exactly sure what the contents of the datas dictionary represents. But if you're trying to use loops to simplify the construction, then the following creates what you want.

datas = {
    '1': {i: 'TESTa' for i in range(3)},
    '2': {i: 'TESTb' for i in range(3)},
    '3': {i: 'TESTc' for i in range(3)}
}
Gary Kerr
  • 13,650
  • 4
  • 48
  • 51
  • Thanks for the insights. I just tested but got this error `KeyError: '1'` full error here: https://pastebin.com/9sDx10mu https://i.imgur.com/tvtWKCC.png For the overwriting I thought it wouldn't matter for the use case as the `datas` dict will be emptied before each new use. I found a fix from here to the KeyError https://bobbyhadz.com/blog/python-keyerror-1 , with new MRE here: https://pastebin.com/VBxbhXWv but it's not fixing the issue. – Lod Nov 24 '22 at 23:24
  • It outputs `{'1': {2: 'TESTa'}}` when outside the loop (only when inside the loop does it output `{'1': {0: 'TESTa'}} {'1': {1: 'TESTa'}} {'1': {2: 'TESTa'}}` – Lod Nov 24 '22 at 23:25
  • Any idea why it's not working? I thought it might be my `datas['1'] = {}` from line 20 here https://pastebin.com/VBxbhXWv but I'm not sure where to pinpoint the issue. Thanks for your help! – Lod Nov 24 '22 at 23:26