问题描述
我有两个长度不等的字典,例如:
I've got two dictionaries of unequal length, e.g.:
people = {"john" : "carpenter", "jill": "locksmith", "bob":"carpenter", "jane": "pilot", "dan": "locksmith"}
jobcode = {"carpenter": 1, "locksmith": 2, "pilot": 3}
我想要做的是将people
中的值替换为jobcode
值.因此,您最终会得到:n
What I'm wanting to do is replace the values in people
with the jobcode
value.So youd end up with:n
people = {"john": 1, "jill": 2, "bob": 1, "jane": 3, "dan":2}
我很乐意制作另一个也封装了这些新数据的新dict
,但到目前为止,我认为最接近的是 ...我认为...
I'd be happy to make another new dict
that encapsulates this new data as well but so far the closest I think I've come is this... I think...
任何帮助将不胜感激.
推荐答案
您可以通过dict理解轻松实现这一目标
You can easily achieve this with dict comprehension
{k: jobcode[v] for k, v in people.items()}
但是您应该小心,因为它可以提高KeyError
.
However you should be careful since it can raise KeyError
.
使用默认jobcode
和dict
方法:
default_jobcode = 1000
final_dict = {k: jobcode.get(v, default_jobcode) for k, v in people.items()}
更新
如 @Graipher 所述,如果jobcode
dict缺少键值对,则可以保留项目保持原样:
As @Graipher kindly noted, if jobcode
dict is lack of key-value pair, you can leave item untouched as such:
final_dict = {k: jobcode.get(v, v) for k, v in people.items()}
使用默认的jobcode
可能是更好的解决方案.
Which is probably better solution that having default jobcode
.
这篇关于Python字典:如何根据键更新字典值-使用单独的字典键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!