Is there any equivalent of in-place slice assignment for dict objects?

时间:2019-02-18 00:23:46

标签: python dictionary

In Python, the content of a list instance can be transformed nicely using a list comprehension—for example:

lst = [item for item in lst if item.startswith( '_' )]

Furthermore, if you want to change lst in place (so that any existing references to the old lst now see the updated content) then you can use the following slice-assignment idiom:

lst[:] = [item for item in lst if item.startswith( '_' )]

My question is: is there any equivalent to this for dict objects? Sure, you can transform content using a dict comprehension—for example:

dct = { key:value for key,value in dct.items() if key.startswith( '_' ) }

but this is not an in-place change—the name dct gets re-bound to a new dict instance. Since dct{:} = ... is not legal syntax, the best I can come up with to change a dict in-place is:

tmp = { key:value for key,value in dct.items() if key.startswith( '_' ) }
dct.clear()
dct.update(tmp)

Any time I see a simple operation require three lines and a variable called tmp, I tend to think it's not very Pythonic. Is there any slicker way to do this?

edit: I guess the filtering and the assignment are separate issues. Really this question is about the assignment—I want to allow arbitrary transformations of the dict content, rather than necessarily just selective removal of some keys.

0 个答案:

没有答案