-1

I know this is simple, but I just can't figure it out. I have a bunch of keys in a dictionary, a large portion of which end with "*". I want to keep those keys but remove the asterisk.

for key, value in network.items():
        if key.endswith('*'):
            network[key.replace("*", "")] = network.pop(key)

The code runs, but the asterisks remain! Any insights as to why this is happening?

Timur Shtatland
  • 12,024
  • 2
  • 30
  • 47
  • You cannot add or delete keys while iterating through a dictionary. The result is undefined. Your best bet is `network = {key.replace("*", ""): value for key, value in network.items()} which builds a new dictionary. – Frank Yellin Dec 22 '20 at 02:23
  • You are modifying the dict while iterating over it. Try `for key, value in list(network.items())` if the dict isn't too large. – Michael Butscher Dec 22 '20 at 02:24
  • 1
    @PM77-1. The `pop()` is removing the old keys. That's not what the problem is. – Frank Yellin Dec 22 '20 at 02:24

1 Answers1

0

Use re.sub and dict comprehension like so:

import re
network = {'k1': 'v1', 'k2*': 'v2', 'k3': 'v3', 'k4*': 'v4'}
network = {re.sub(r'[*]$', '', k): v for (k, v) in network.items()}
print(network)
# {'k1': 'v1', 'k2': 'v2', 'k3': 'v3', 'k4': 'v4'}
Timur Shtatland
  • 12,024
  • 2
  • 30
  • 47