Home > database >  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

Time:12-06

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.

CodePudding user response:

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.

CodePudding user response:

To update a dictionary in the way you describe, you can use the dict.get() method to lookup the values associated with the keys '5' and '2' in the dictionary, and then use string concatenation to combine these values with the existing value for the '12' key in the dictionary. Here is an example of how you could do this:

# Create the dictionary
dict = { '12' : '5 2',
         '5' : 'xyz',
         '2' : 'abc' }

# Look up the values associated with the keys '5' and '2'
key5 = dict.get('5')
key2 = dict.get('2')

# Concatenate the values to create the new value for the '12' key
newValue = key5   " "   key2

# Update the dictionary
dict['12'] = newValue

# Print the updated dictionary
print(dict)

This code will create the initial dictionary, look up the values associated with the '5' and '2' keys, concatenate these values to create the new value for the '12' key, update the dictionary with this new value, and then print the updated dictionary. The output of this code will be:

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

I hope this helps. Let me know if you have any other questions.

CodePudding user response:

@Omerdan

The naming of your variables is misleading.

key5 = dict.get('5') key2 = dict.get('2')

it should say value5 and value2, since dict.get('') gets you the value and not the key. The key is already known at this point.

  • Related