Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Iterating over dictionary by skipping the first key-value

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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 you’re a >= Python 3.7 user:
Okay if you really wanted to rely on the techincal implementation of a version specific feature, you can 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading