Home > Mobile >  Iterating over dictionary by skipping the first key-value
Iterating over dictionary by skipping the first key-value

Time:11-16

I have defined a dictionary with a key and a dataframe, like this

data = {'Value':[0,1,2,3,4]}
kernel_df = pd.DataFrame(data, index=['M0','M1','M2','M3','M4'])
my_dict = {'dummy':kernel_df}

And my_dict is later filled with appropriate data. Next, I want to iterate over the dictionary starting from the second key, because the first (index 0) is dummy and I want to skip that. If I use

for key in my_dict:

Then the first key is also read. If I use

for i in {1..len(my_dict)}:
    df = my_dict[i]

I receive the following error

    for i in {1..len(my_dict)}:
AttributeError: 'float' object has no attribute 'len'

How can I fix that?

CodePudding user response:

A dictionary doesn't have an inherent order(well okay, things changed in Python 3.7 where they now maintain the order of insertion.

However, you still can't index a dictionary like you would index a list. (Okay you can get close to that kind of behavior if you really so wished, but I'll address that towards the end).

In your case, you can just iterate through the keys and skip the key if it's 'dummy' (or whatever you've defined it as).

for key in my_dict:
    if key != 'dummy':
        do your thing

Perhaps a better alternative would be to simply remove the 'dummy' key once you know your dictionary has bee populated with proper values.

Now, coming back to getting the 'first key' because one is a >= Python 3.7 user:
Okay if someone really wanted to rely on the technical implementation of a version specific feature, they could probably do something like this:

for idx, key in enumerate(my_dict.keys()):
    if idx != 0:
        do your thing

This is far from idiomatic code though, so really, you shouldn't.

  • Related