Python: changing the dictionary returned by groupdict ()

Is it possible to change the changed object returned by the standard library object method?

Here is one specific example; but I am looking for a general answer if possible.

#m is a MatchObject
#I know there only one named group in the regex
#I want to retrieve the name and the value
g, v = m.groupdict().popitem()
#do something else with m

Is this code safe? I'm worried that by modifying groupdict () I am distorting the m object (which I still need for later).

I checked this, and the subsequent call to m.groupdict () still returned the original dictionary; but for everyone I know, this may be implementation dependent.

+5
source share
4 answers

, , . ( , -, .)

+1

groupdict :

In [20]: id(m.groupdict())
Out[20]: 3075475492L

In [21]: id(m.groupdict())
Out[21]: 3075473588L

. , . groupdict . .

0

, MatchObject.groupdict() , , .

dict.popitem() , , .

(, ) .

popitem() , . , popitem() a KeyError.

0
source

mTwo different operations are performed here . First, groupdictcreates a dictionary from m. The second popitem,, returns an element from the dictionary and modifies the dictionary (but not the base element).

Thus, subsequent calls m.groupdict()still create a dictionary from the same m.

But why do you use popitemat all? Why not easy items()?

0
source

All Articles