0

I am trying to loop through iterator with offset [i+1].

I have enumerated my dict. Now I want to access dfc with function offsetting second dataframe.

dfc = dict() 
mydict = {1: 6, 2: 4,3: 10, 4: 7, 5: 3}
for i, (k, v) in enumerate(mydict.items()):
    dfc[(i)] = v
    print("index: {}, key: {}, value: {}".format(i, k, v))      

for i in range(0,5,1):
   result[i] = dfc[i] * dfc[i+1]

But I got this error:

  File "<ipython-input-139-b31501e8f8af>", line 2, in <module>
    result[i] = dfc[i] * dfc[i+1]

KeyError: 5
JoYSword
  • 432
  • 1
  • 3
  • 14
  • 1
    The keys of `dfc` run from 0 to 4 (see the enumerate part), not from 1 to 5. Hence you get a KeyError. – 9769953 Jun 13 '19 at 15:24
  • 1
    If you want to add one "row" of your "dataframe" to the next "row", remember that there will always be one missing: you can't iterate over all items, because what would be the next item for the last item? – 9769953 Jun 13 '19 at 15:25
  • Ah ok many thanks...can this offset be applied to directly to dictionary key value? for k in dfb: adf_19 = dfb[k] adf_20 = np.dot(dfb[k+1], dfb[k]) – Pat Tierney Jun 13 '19 at 15:30

1 Answers1

0

You access non existing keys, thats why the error. You can fix this:

mydict = {1: 6, 2: 4, 3: 10, 4: 7, 5: 3}
# there is no sense in creating dfc - if you need a dublicate, use dfc = dict(mydict)
sorted_keys = sorted(mydict) # sort keys - dicts are unordered / insert ordered from 3.7 on

for k in sorted_keys: 
    print(f"index: {k}, key: {k}, value: {mydict[k]}")

result = {}
for i in sorted_keys:
    result[i] = mydict[i] * mydict.get(i+1,1)  # avoid key error, if not existst, mult by 1

for k in sorted_keys: 
    print(f"index: {k}, key: {k}, value: {result[k]}")

Output:

index: 1, key: 1, value: 6
index: 2, key: 2, value: 4
index: 3, key: 3, value: 10
index: 4, key: 4, value: 7
index: 5, key: 5, value: 3

index: 1, key: 1, value: 24
index: 2, key: 2, value: 40
index: 3, key: 3, value: 70
index: 4, key: 4, value: 21
index: 5, key: 5, value: 3

Using dict.get(key,default) allows to try to get the value and if not present allows a default 1. 1*whatever wont change the result.

See Why dict.get(key) instead of dict[key]?

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69