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

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

Contents

Problem Description:

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.

## Solution – 1

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.

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

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

## Solution – 2

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'}
``````
Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.