简体   繁体   中英

Replace value of a given key with value of another given key in Python Dictionary

I have a dictionary like

dict = { '12' : '5+2',
         '5' : 'xyz',
         '2' : 'abc' }

so I want updated dictionary to be like

dict = { '12' : 'xyz+abc',
         '5' : 'xyz',
         '2' : 'abc' }

Note: It is known to me that key '12' has value containing '5' and '2' hence no iteration is required, I just want to replace 5 with xyz and 2 with abc. Please suggest.

You just do a chained reassignment:

dict['<key2>'], dict['<key1>'] = dict['<key1>'], dict['<key2>']

That's a swap operation.

It should work to also concatenate dict values referenced by their key. In your case:

dict1['12'] =  dict1['5'] + "+" + dict1['2']

Also I would advise you to not use python keywords like "dict" as variable names.

I would use a regex in a dictionary comprehension:

dic = {'12' : '5+2', '5' : 'xyz', '2' : 'abc'}

import re

# create the regex from the keys
# use the longer strings first to match "12" before "2"
pattern = '|'.join(map(re.escape, sorted(dic, key=lambda x: -len(x))))
# '12|5|2'

out = {k:re.sub(pattern, lambda m: dic.get(m.group()), v) for k,v in dic.items()}

Output:

{'12': 'xyz+abc', '5': 'xyz', '2': 'abc'}

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