简体   繁体   中英

How to replace the first character of all keys in a dictionary?

What is the best way to replace the first character of all keys in a dictionary?

old_cols= {"~desc1":"adjustment1","~desc23":"adjustment3"}

I am trying to get

new_cols= {"desc1":"adjustment1","desc23":"adjustment3"}

I have tried:

for k,v in old_cols.items():
    new_cols[k]=old_cols.pop(k[1:])
old_cols = {"~desc1":"adjustment1", "~desc23":"adjustment3"}
new_cols = {}

for k, v in old_cols.items():
    new_key = k[1:] 
    new_cols[new_key] = v

Here it is with a dictionary comprehension:

old_cols= {"~desc1":"adjustment1","~desc23":"adjustment3"}

new_cols = {k.replace('~', ''):old_cols[k] for k in old_cols}

print(new_cols)
#{'desc1': 'adjustment1', 'desc23': 'adjustment3'}

There are many ways to do this with list-comprehension or for -loops. What is important is to understand is that dictionaries are mutable. This basically means that you can either modify the existing dictionary or create a new one.

If you want to create a new one (and I would recommend it! - see 'A word of warning...' below), both solutions provided in the answers by @Ethem_Turgut and by @pakpe do the trick. I would probably wirte:

old_dict = {"~desc1":"adjustment1","~desc23":"adjustment3"}
# get the id of this dict, just for comparison later.
old_id = id(old_dict)

new_dict = {k[1:]: v for k, v in old_dict.items()}

print(f'Is the result still the same dictionary? Answer: {old_id == id(new_dict)}')

Now, if you want to modify the dictionary in place you might loop over the keys and adapt the key/value to your liking:

old_dict = {"~desc1":"adjustment1","~desc23":"adjustment3"}
# get the id of this dict, just for comparison later.
old_id = id(old_dict)

for k in [*old_dict.keys()]:  # note the weird syntax here
    old_dict[k[1:]] = old_dict.pop(k)

print(f'Is the result still the same dictionary? Answer: {old_id == id(old_dict)}')

A word of warning for the latter approach:

You should be aware that you are modifying the keys while looping over them. This is in most of the cases problematic and can even lead to a RuntimeError if you loop directly over old_dict . I avoided this by explicitly unpacking the keys into a list and the looping over that list with [*old_dict.keys()] .

Why can modifying keys while looping over them be problematic? Imagine for example that you have the keys '~key1' and 'key1' in your old_dict . Now when your loop handles '~key1' it will modify it to 'key1' which already exists in old_dict and thus it will overwrite the value of 'key1' with the value from '~key1' .

So, only use the latter approach if you are certain to not produce issues like the example mentioned here before. If you are uncertain, simply create a new dictionary!

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