简体   繁体   中英

Going through a dictionary with tuples in Python

I have a dictionary in Python where inside it there are a list of tuples. An example of it is:

peers = {'hash1': [('bot2', 1), ('bot1', 1)]}

I want to do a function called "update" that take all the dictionary and, if in tuple there is a number one, become 0 and, if it's 0, delete the tuple.

The loop that I implemented is this:

def update(self):
        for key in self.peers.keys():
            for tup in self.peers[key]:
                print "--"
                print tup
                if 0 in tup:
                    self.peers[key].remove(tup)
                else:
                    newTup = (tup[0], 0)
                    self.peers[key].remove(tup)
                    self.peers[key].append(newTup);

If I do two "update", the correct behaviour should be that in the first update I should have the tuples at 0 and in the next I should have an empty dictionary with key 'hash1'. But in the real behaviour I take it:

First update:

peers = {'hash1': [('bot1', 1)]}

(Two updates in one? Why?)

Second update:

peers = {'hash1': [('bot1', 0)]}

(Oh! This update is correct, but why not the first one?)

Can someone help me with that loop? I don't know why it has this behaviour... I think that loop is correct but...

Thanks!

Like Ev. Kounis said - you should not try to modify the list you iterate over.

You could do it this way:

def update(self):
  for key in self.peers.keys():
    peers_temp = self.peers[key].copy()
    for tup in self.peers[key]:
      print("--")
      print(tup)
      if 0 in tup:
        peers_temp.remove(tup)
      else:
        newTup = (tup[0], 0)
        peers_temp.remove(tup)
        peers_temp.append(newTup);
      self.peers[key] = peers_temp

@Edit: It works for Python 3. For older versions change peers_temp = self.peers[key].copy() for peers_temp = list(self.peers[key])

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