Add all loop values into dictionary

Hello again All…i really need help, spending time already. I have a code below, i want to add all loop values into dict. I tried but dont understand why only half is in the dict. Please help me fix…thanks

###Duplicate @ Y
from collections import defaultdict
import pandas as pd

def dup_y():
        df = pd.DataFrame(
            [
                (76, 44),
                (32, 45),
                (77, 44),
                (78, 44),
                (78, 34),
                (78, 45),
                (45, 44),
                (87, 54),
                (34, 23),
                (76, 45),
                (54, 58),
                (95, 34),
                (77, 45),
                (84, 45),
            ], columns=('Y', 'X')
        )

        entries = defaultdict(list)

        for x, y in zip(df.loc[ : , 'X'], df.loc[ : , 'Y']):
            entries[x].append(y)

        #print('X\tY')
        dict_xc = {}
        for x, y_list in entries.items():
            y_list.sort()

            for start in range(len(y_list) - 2):
                if y_list[start] == y_list[start + 1] - 1 == y_list[start + 2] - 2:
                    for y in y_list[start : start + 3]:
                        print(f'{y}\t{x}')
                        dict_xc[y] = x
                        #print(dict_xc)
        return dict_xc

Output:

76 44
77 44
78 44
76 45
77 45
78 45

{76: 45, 77: 45, 78: 45}


Here is my expected outout:

76	44
77	44
78	44
76	45
77	45
78	45
{76: 44, 77: 44, 78: 44, 76: 45, 77: 45, 78: 45}

A dict cannot contain duplicate keys. In your expected output, the keys 76, 77 and 78 occur twice. That’s not allowed. If you try that, the later value overwrites the earlier value.

1 Like

oh i see…i will try with list…or is there other ways? thanks

Well, instead of dict_xc[y] = x, you could use dict_xc.setdefault(y, x). This will remember only the first value (the lowest one), giving you {76: 44, 77: 44, 78: 44}.

You know that each value is the first of a sequence of 3, increasing in steps of 1, so why store the whole sequence? You can easily recreate the sequence later, if it’s needed.

1 Like