1

I have a Python dictionary with the following form:

data = {'2022-01-01': [123, 456], '2022-01-02': [789, 120], ... }

I am trying to loop over the dictionary data and divide the two numbers contained in the lists (e.g. 123/456, 789/120, etc.) with the following:

for values in len(range(data)):
    ratio = values[0]/values[1]

But I get a TypeError saying that the dict object cannot be interpreted as an integer. My numbers are clearly integers. Is this not the correct way to loop across a dictionary?

Also, is there a way that I can store the resulting ratio along with the dates in either a new dictionary or a pandas data frame?

martineau
  • 119,623
  • 25
  • 170
  • 301
user318369
  • 27
  • 5
  • 2
    When you researched iterating over a `dict`, what ways did you find of doing that? – quamrana Feb 17 '22 at 17:57
  • data is a dictionary. you are calling data like it is a function(it is not callable). Try using `values` variable which is defined in the loop using `items` function on the dictionary. – TheFaultInOurStars Feb 17 '22 at 17:58
  • @quamrana I get the same error with this method: ```for values in len(range(datesUserRisk)): ratio = values[0]/values[1]``` – user318369 Feb 17 '22 at 17:59
  • 1
    So, does that indicate to you that you aren't using one of the valid ways of iterating over a `dict`? – quamrana Feb 17 '22 at 18:00
  • why are you doing `for values in len(range(data))`? What do you think that does? For starters, `len` returns an `int` always, so `for values in some_int` would never work, since `int` objects are not iterable. Usually you mean `range(len(data))`, but in this case, that would iterate over a `range` object, not a dictionary... Have you looked up how to iterate over a dictionary? – juanpa.arrivillaga Feb 17 '22 at 18:02

2 Answers2

3

data is a dictionary, not a function, so you shouldn't use parenthesis to attempt to access it.

You should also be iterating over data.items(), not len(range(data)). You're iterating over the keys of a dictionary, not a list.

With these two corrections, we get the following:

for key, values in data.items():
    ratio = values[0]/values[1]
BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33
1

Also worth mentioning:

len(range(data)) is just a number. for key, value in 123 (for instance) does not make sense. To iterate the key, value pairs of a dictionary (named data), you need to do for key, value in data.items().

You don't need the keys in order to produce your desired output, so there's no need to iterate the key, value pairs, just the values. To iterate just the values, do for value in data.values().

Orius
  • 1,093
  • 5
  • 11