Home > Mobile >  How do I fill a dictionary with indices in a for loop?
How do I fill a dictionary with indices in a for loop?

Time:12-04

I have a transposed Dataframe tr:

7128 8719 14051 14636
JDUTC_0 2451957.36 2452149.36 2457243.98 2452531.89
JDUTC_1 2451957.37 2452149.36 2457243.99 2452531.90
JDUTC_2 2451957.37 2452149.36 2457244.00 2452531.91
JDUTC_3 NaN 2452149.36 NaN NaN
JDUTC_4 NaN 2452149.36 NaN NaN
JDUTC_5 NaN 2452149.36 NaN NaN
JDUTC_6 1.23 2452149.37 NaN NaN
JDUTC_7 NaN NaN NaN NaN
JDUTC_8 NaN NaN NaN NaN
JDUTC_9 NaN NaN NaN NaN

And I create dict 'a' with this block of code:

a = {}
b=[]
for _, contents in tr.items():
    b.clear()
    for ind, val in enumerate(contents):
        if np.isnan(val):
            b.append(ind)
            continue
        else:
            pass
    print(_)
    print(b)
    a[_] = b
    print(a)

Which gives me this output:

7128
[3, 4, 5, 7, 8, 9]
{7128: [3, 4, 5, 7, 8, 9]}
8719
[7, 8, 9]
{7128: [7, 8, 9], 8719: [7, 8, 9]}
14051
[3, 4, 5, 6, 7, 8, 9]
{7128: [3, 4, 5, 6, 7, 8, 9], 8719: [3, 4, 5, 6, 7, 8, 9], 14051: [3, 4, 5, 6, 7, 8, 9]}
14636
[3, 4, 5, 6, 7, 8, 9]
{7128: [3, 4, 5, 6, 7, 8, 9], 8719: [3, 4, 5, 6, 7, 8, 9], 14051: [3, 4, 5, 6, 7, 8, 9], 
14636: [3, 4, 5, 6, 7, 8, 9]}

What I expect dict 'a' to look like is this:

{7128: [3, 4, 5, 7, 8, 9]
 8719: [7, 8, 9]
14051: [3, 4, 5, 6, 7, 8, 9]
14636: [3, 4, 5, 6, 7, 8, 9]}

What I am doing wrong? Why is a[_] = b overwriting all the previous keys when print(_) is verifying that _ is always the next column label?

CodePudding user response:

The problem is you are assigning same list to all keys.

a = {}
b=[] # < --- You create one Array/list 'b'
for _, contents in tr.items():
    b.clear()
    for ind, val in enumerate(contents):
        if np.isnan(val):
            b.append(ind)
            continue
        else:
            pass
    print(_)
    print(b)
    a[_] = b # <-- assign same array to all keys.
    print(a)

Check my comment on the code above.

b.clear()

This line just clears the same array, it does not create a new array.

To run the code as you intended, create a new array/list in side the loop.

a = {}
for _, contents in tr.items():
    b = [] # <--- new array/list is created
    for ind, val in enumerate(contents):
        if np.isnan(val):
            b.append(ind)
            continue
        else:
            pass
    print(_)
    print(b)
    a[_] = b # <--- Now you assign the new array 'b' to a[_]
    print(a)
  • Related