[Tutor] Remove a dictionary entry

M. 427 427 at free.fr
Sun Sep 19 02:39:18 CEST 2010


Version 4 : (2 steps)

	# step 1 : list keys of unwanted rows
	sck=[] # list of single children keys in dictionary
	for k in d.keys() :
		if len(d[k]) < 2 :
			sck.append(k)
	# step 2 : delete all d rows whose key is listed in sck
	while len(sck) > 0 :
		del d[sck.pop()]

This works.
Is this the optimal pythonic way of doing it?

Mr. 427


Le vendredi 17 septembre 2010 à 21:36 -0400, bob gailer a écrit :
> On 9/17/2010 9:21 PM, M. 427 wrote:
> > Thank you,
> > After reading the following documentations
> > http://docs.python.org/tutorial/datastructures.html#looping-techniques
> > http://docs.python.org/tutorial/controlflow.html#for-statements
> > I ended up with this :
> >
> > Version 3 :
> > for i,row in d[:].iteritems() : # BUG : TypeError: unhashable type
> >      if len(row)<  2 :
> >          del d[i]
> >
> > Still buggy... Any lead for this error message? Is a slice unhashable?
> > Am I looking in the right direction for this task?
> Where did you see [:] after a dict? [:] is slicing, and applies to a 
> sequence not a mapping.
> 
> Also note the warning "Using iteritems()  while adding or deleting 
> entries in the dictionary may raise a RuntimeError  or fail to iterate 
> over all entries."
> 
> You should get a list rather than an iterator of all key-value pairs 
> then iterate over that list.
> 




More information about the Tutor mailing list