Change key value in for loop, regardless of the current value in Python

I'm running a for loop on a dictionary, and I need to alter the Key if it starts with "C-" to a specific string, regardless on what follows after the C-

Sample data:

 {'H-NSW-BAC-ENG': 15, 'C-NSW-BAC-ENG': 15, 'H-NSW-BAC-FBE': 30, 'C-NSW-BAC-FBE': 30, 'G-NSW-BAC-ENG': 15, 'G-NSW-BAC-FBE': 30}

Method I'm using to do so:

def transform_caps_keys(d):
    for k, v in d.items():
        if k[0:1] == 'C':
            k = "C-STD-B&M-SUM"
            print(k)
    print(d)

I need 'C-NSW-BAC-ENG' and 'C-NSW-BAC-FBE' to be changed to 'C-STD-B&M-SUM'.

When I print k, I get the keys I want, but they are not changed within the dictionary.

I also tried:

def transform_caps_keys(d):
for k, v in d.items():
    if k[0:1] == 'C':
        d['C-STD-B&M-SUM'] = d.pop(k)
        print(k)
print(d)

But I get the following error:

RuntimeError: dictionary changed size during iteration

Upvotes: 0

Views: 673

Answers (2)

Marius M
Marius M

Reputation: 496

You cannot alter an iterable collection while iterating it (the keys collection), moreover - any "edit" over a key in a dictionary means a new key in that dictionary, long story short you'll need a new dictionary based on your altering rules.

Upvotes: 1

sachin saxena
sachin saxena

Reputation: 976

    def transform_caps_keys(d):
        for k, v in d.items():
            if k[0:1] == 'C':
                val = "C-STD-B&M-SUM"
                d[val] = d[k]
                del d[k]
        print(d)

Upvotes: 0

Related Questions