简体   繁体   中英

for loop skipping sections of dictionary in python

GeoFigs =  {'Populus':0, 'Tristidia':1, 'Albus':2, 'Fortuna Major':3, 'Rubeus':4,
            'Acquisitio':5, 'Conjunctivo':6, 'Caput Draconis':7, 'Laetita':8, 'Carcer':9, 
            'Amissio':10, 'Puella':11, 'Fortuna Minor':12, 'Puer':13, 'Cauda Draconis':14, 'Via':15}
KeyGeo = dict.copy(GeoFigs)
for key in KeyGeo:
    print KeyGeo[key]
    keychange = KeyGeo[key]
    newValue = key
    del KeyGeo[key]
    KeyGeo[keychange] =  newValue

When I run the for loop it skips over some of the keys producing

(0, 'Populus'), (1, 'Tristidia'), ('Carcer', 9), (3, 'Fortuna Major'), (4, 'Rubeus'),
(5, 'Acquisitio'), (6, 'Conjunctivo'), (7, 'Caput Draconis'), ('Puer', 13), (10, 'Amissio'),
(11, 'Puella'), (12, 'Fortuna Minor'), (2, 'Albus'), (14, 'Cauda Draconis'), (15, 'Via'), ('Laetita', 8)]

Any idea why it's skipping the 3rd and the 9th only?

There are two issues at play here:

  1. The ordering of keys in a dict is not defined. If you care about the ordering, using something like OrderedDict .
  2. You are making structural changes to the dict while iterating over it. See Modifying a Python dict while iterating over it

Others have nailed the problem - you are changing the dict as you iterate. You solve the problem by getting a copy of the keys before you start. Its a bit different in python 2 and 3. In python 2, keys is a list:

for key in KeyGeo.keys():
    ...

In python 3, keys is an iterator so you have to iterate before you start

for key in list(KeyGeo.keys()):
    ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM