[Tutor] deleting elements of a dictionary

Mats Wichmann mats at wichmann.us
Sat May 20 09:05:03 EDT 2017


On 05/19/2017 02:54 PM, Mats Wichmann wrote:
> On 05/19/2017 11:17 AM, Alan Gauld via Tutor wrote:
>> On 19/05/17 15:23, Michael C wrote:
>>> list(read_dictionary) converts the dictionary into a list right? How can
>>> you save the list as a dictionary?
>>
>> Nope, list() produces a new list object containing the
>> keys of the dictionary. In the old day(of python 2) you
>> used to get the same effect using
>>
>> for key in mydict.keys()
>>
>> but keys() now returns a funky view of the original dict
>> keys and I suspect you'd have the same problems when
>> deleting items. So Peter's list() is probably the best
>> option.
>>
> 
> Or to take another related view:
> 
> don't remove items from an iterable while iterating over it: del() is
> okay as long as you're not looping over the thing.
> 
> Dictionaries have a method for this called pop(), but to my blushes, I
> don't really have a lot of experience with it.
> 
> What I'd think of just off the bat is build a new dictionary on the fly,
> omitting the things you were trying to delete, and then if you like,
> save the new dict by the old name (which will cause the old one to have
> no references and be dropped.

Having now done a quick check, mydict.pop() is no better for this case.

Here's a simplistic sample that does work:

d = {
    100:3,
    200:4,
    111:5,
    222:5,
    333:5,
    500:6,
}

print "original: ", d

new = {key:value for (key,value) in d.iteritems() if value != 5}

print "new: ", new



More information about the Tutor mailing list