[英]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.我已经回顾了有关 stackoverflow 的许多问题,其中所做的是通过 for 循环迭代字典并更改特定键的值。
Like this:像这样:
for key, value in inputdict.items():
inputdict[key] = newvalue
Or just using update
.或者只是使用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 相同,但我想将键brand
和model
的值“合并”到品牌键中。
(dict1) Ford -> (dict2) Ford 1964
How can I do that?我怎样才能做到这一点?
This perhaps?这也许?
dict2 = dict1.copy()
dict2['brand'] = ' '.join([dict2["brand"], dict2["year"]])
How about this?这个怎么样?
def dict_update(dict1):
dict2 = {}
for key in dict1:
if key == 'brand':
dict2[key] = str(dict_['brand'])+' '+str(dict_['year'])
elif key not in dict2:
dict2[key] = str(dict_[key])
return dict2
So this is what I did:所以这就是我所做的:
dict2 = {}
for key, value in dict1.items():
if key == 'brand':
for key2, value2 in dict1.items():
if key2 == 'year':
dict2[key] = str(value) + " " + str(value2)
else:
dict2[key] = value
It works but I don't know if it's the most optimal solution (I don't like nesting for loops...but it's the only way I can think of to make it work)它可以工作,但我不知道它是否是最佳解决方案(我不喜欢嵌套 for 循环......但这是我能想到的让它工作的唯一方法)
Is there any other way to get the same result in python without importing libraries?有没有其他方法可以在不导入库的情况下在 python 中获得相同的结果?
Any suggestions will be appreciated任何建议将不胜感激
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.