Qn: Nested dictionary cleanup

Skip Montanaro skip at pobox.com
Mon Nov 3 16:20:30 EST 2003


    Colin> for key1 in dict1.keys():
    Colin>     for key2 in dict1[key1]:
    Colin>         if dict1[key1][key2] == None:
    Colin>             del dict1[key1][key2]

Should be

    for key1 in dict1.keys():
        for key2 in dict1[key1].keys():
            if dict1[key1][key2] == None:
                del dict1[key1][key2]

Note that the inner for loop explicitly calls .keys().  That creates an
explicit list.  You loop over that instead of an iterator.  Why did you
choose to call dict1.keys() but not dict1[key1].keys()?

Skip





More information about the Python-list mailing list