-3

I want to construct a list containing some dict using list comprehensions. I tried to use .update() but get None.

For examples

  >>> data = [ {}.update({'demo': i}) for i in range(5) } ]
  >>> data
  [None, None, None, None, None]

While what I want is:

  [ {'demo': 0}, {'demo': 1}, {'demo': 2}, {'demo': 3}, {'demo': 4}]

Any idea? thx.

As for coldspeed's confusion, the example above is just a simple demo, what if {} is not an empty directory but arbitrary directory? If we just need to update each item which is dict in a list using list comprehensions, I think maybe we can't avoid update. That's why I came up with .update().

Sorry for my poor information in the first time.

jianjieluo
  • 319
  • 1
  • 4
  • 15

1 Answers1

1

As coldspeed said in a comment to your question:

What's wrong with [{'demo': i} for i in range(5) } ]?

The problem with the code you have shown is:

update is an in-place operation, so it returns None and updates the dictionary in-place, before its reference is lost and it is garbage collected.

However, let us give you the benefit of the doubt, and assume that your actual problem is a little bit more complicated. The solution is to define a small function:

def f(i):
    result = {}
    result.update({'demo': i})
    return result

data = [ f(i) for i in range(5) } ]

Obviously, you would only do this if you have an actual need for the additional complexity.

  • Thx, it is helpful. I can use a function wrapper to return a new dict object in the list comprehensions to solve the problem while I wonder whether there's any briefer solution. I will accept your answer if there are no more briefer solution. Thx once more. – jianjieluo Dec 23 '18 at 09:34