2021年4月11日星期日

How to create a new dictionary from another one by modifying specific values (join the values of two keys into one)

I have reviewed many questions on stackoverflow where what is done is to iterate a dictionary through a for loop and change the value for a specific key.

Like this:

for key, value in inputdict.items():      inputdict[key] = newvalue  

Or just using update.

I have not found an answer for this specific case and the truth is that I do not know very well how to proceed.

Let's say I have the following dictionary:

dict1 = {    "brand": "Ford",    "model": "Mustang",    "year": "1964"  }  

And let's say I want a new dictionary (copying the previous dictionary but modifying the value of a certain key):

dict2 = {    "brand": "Ford 1964",    "model": "Mustang",    "year": "1964"  }  

Basically I want the same as dict1, but I want to 'merge' the values of the keys brand and model into the brand key.

(dict1) Ford -> (dict2) Ford 1964

How can I do that?

https://stackoverflow.com/questions/67051965/how-to-create-a-new-dictionary-from-another-one-by-modifying-specific-values-jo April 12, 2021 at 10:29AM

没有评论:

发表评论