0

I have a dictionary and as I am creating it during list comprehension can I access the previous values created?

Example:

h = {i:1+h[i-1] for i in range(1,100))}
277roshan
  • 354
  • 1
  • 3
  • 13
  • No. And if you need that, a list comprehension is not the right tool as, per definition, it means the element are handled independently. Maybe have a look at itertools functions such as [`accumulate()`](https://docs.python.org/3/library/itertools.html#itertools.accumulate). – spectras Nov 08 '16 at 07:17
  • You call it "list comprehension" but you build dictionary. Unfortunately you cannot use it so. Since the variable h will point to the new dict object only when it has been created, you cannot access it before. You can do it with a for loop. – quantummind Nov 08 '16 at 07:20
  • What Python version? – Laurens Koppenol Nov 08 '16 at 07:22
  • @quantummind they are stil called list comprehension. Such operations are all termed under that I guess. My python version is 3.4.4 – 277roshan Nov 08 '16 at 07:23
  • 4
    It's a dict comprehension. A list comprehension applies only to building lists. I'd imagine a more general term of comprehension would be applicable. – Paul Rooney Nov 08 '16 at 07:25
  • 1
    @277roshan No, it is called a dictionary comprehension. See for example, the [PEP](https://www.python.org/dev/peps/pep-0274/). – juanpa.arrivillaga Nov 08 '16 at 07:26
  • @277roshan you'd have to give up on the comprehension and generate it in a manual loop. – Paul Rooney Nov 08 '16 at 07:26
  • @277roshan "dict comprehension" or "dictionary comprehension" are used as well. I understand your point but in that case in subject I would put "for dictionary" to be more precise. – quantummind Nov 08 '16 at 07:30

1 Answers1

1

Edit: I read i:i + h[i-1] instead of i:1 + h[i-1]. The latter is always equal to i:i except in the first case, when it is 1+None

This does what you want in a dictionary comprehension. Requires Python 3.2 or higher:

from itertools import accumulate 
h = {i:v for i,v in enumerate(accumulate(range(100)))}

otherwise use this

def accumulate(r):
    next_value = 0
    for i in r:
        next_value = next_value + i
        yield next_value
Laurens Koppenol
  • 2,946
  • 2
  • 20
  • 33