Skip to content

Trying to understand condensed Python

An answer to this question on Stack Overflow.

Question

I'm trying to understand how this code lays out in long format

proposed = dict((k, v) for k, v in args.iteritems() if v is not None)

The best I can come up with is the following, but it doesn't work:

for k,v in args.iteritems():
    print "value of v is: %s" % v
    if v is not None:
    proposed = dict(k,v)

However it throws the following error:

TypeError: dict expected at most 1 arguments, got 2

Answer

Try:

proposed=dict()
for k,v in args.iteritems():
  print "value of v is: %s" % v
  if v is not None:
    proposed[k] = v #This is the part you got wrong