on a statement followed by an expression

Meredith Montgomery mmontgomery at levado.to
Sat Jun 4 16:18:36 EDT 2022


(*) Question

How can I, in a single line, write a statement followed by an
expression?  For example, if /d/ is a dicionary, how can I write

   d["key"] = value # and somehow making this line end up with d

(*) Where does the question come from?

>From the following experiment-exercise.

(*) Introduction

Here's a gentle way to consome records /rs/, each of which represents a
robbery, say, and produce a dictionary containing a count of each zip
code.

--8<---------------cut here---------------start------------->8---
def zip(r):
  return r[0]

def roberry_per_zip(rs):
  d = {}
  for r in rs:
    d[zip(r)] = dict.get(d, zip(r), 0) + 1
  return d
--8<---------------cut here---------------end--------------->8---

Now I'd like to compare the code with a version that uses reduce.  Let
me please write my own reduce function for completeness and clarity ---
I suppose.  The code is still pretty clear.

--8<---------------cut here---------------start------------->8---
def my_reduce(it, f, init):
  r = init
  for e in it:
    r = f(r, e)
  return r

def count_in(d, r):
  d[zip(r)] = dict.get(d, zip(r), 0) + 1
  return d

def roberry_via_reduce(rs):
  return my_reduce(rs, count_in, {})
--8<---------------cut here---------------end--------------->8---

It's not clear, though, how to write such a procedure using a lambda
expression in place of count_in.  That's because we must return a
dicionary and statements are not expressions.

How can I execute a statement followed by a value in a single line?

def roberry_via_reduce(rs):
  return my_reduce(rs, lambda d, r: ``increment and return d'', {})

I don't know how to write

  ``increment and return d''

I'm just curious.  Thank you.


More information about the Python-list mailing list