Home > database >  How to start from second key when iterating over dictionary using for loop in Python
How to start from second key when iterating over dictionary using for loop in Python

Time:03-24

I am computing returns from data in a dictionary. My keys are dates and for every key I have a dataframe with data to compute my returns. To compute the returns I need data today and yesterday (t and t-1), hence I want to initiate from the second observation (key). Since I do not have much experience my initial thought was to execute like this:

dict_return = {}
for t, value in dict_data.items()[1:]:
   returns = 'formula'
   dict_returns[t] = returns

Which gave me the error:

TypeError: 'dict_items' object is not subscriptable

Searching for an answer, the only discussion I could find was skipping the first item, e.g. like this:

from itertools import islice

for key, value in islice(largeSet.items(), 1, None): 

Is there a simple approach to skip the first key?

Thank you

CodePudding user response:

If you are in Python 3 you need to use a list, Dict_ items ([‘No surfacing ‘,’flippers’]) returns a dict_ The items object is no longer of the list type and does not support index, this is why the list type can be used

CodePudding user response:

I can think of 2 options, both require an extra step:

Option 1: Create a second dict without your key and loop over that

loop_dict = dict_data.pop(<key_to_remove>)

Then loop over loop_dict as you have done above.

Option 2: Create a list of keys from your dict and loop over that

keys = dict_data.keys()
loop_keys = keys[1:]

for key in loop_keys:
    Etc

CodePudding user response:

If you pass a reference to your dictionary to list() you will get a list of the dictionary's keys. This is because dictionaries are iterable. In your code you're not interested in the key's value so:

dict_data = {'a': 1, 'b': 2} # or whatever

dict_data[list(dict_data)[1]] = 3

print(dict_data)

Output:

{'a': 1, 'b': 3}
  • Related