简体   繁体   中英

Python Dictionary: How to update dictionary value, base on key - using separate dictionary keys

I've got two dictionaries of unequal length, eg:

people = {"john" : "carpenter", "jill": "locksmith", "bob":"carpenter", "jane": "pilot", "dan": "locksmith"}

jobcode = {"carpenter": 1, "locksmith": 2, "pilot": 3}

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} 

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...

Any help would be greatly appreciated.

You can easily achieve this with dict comprehension

{k: jobcode[v] for k, v in people.items()}

However you should be careful since it can raise KeyError .

Another way with default jobcode with dict .get() method :

default_jobcode = 1000
final_dict = {k: jobcode.get(v, default_jobcode) for k, v in people.items()}

UPDATE

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()}

Which is probably better solution that having default jobcode .

Ty this:-

people = {'john' : 'carpenter', 'jill': 'locksmith', 'bob':'carpenter', 'jane': 'pilot', 'dan': 'locksmith'}
jobcode = {'carpenter': 1, 'locksmith': 2, 'pilot': 3}
for i,j in people.items():
    if j in jobcode.keys():
        people[i] = jobcode[j]
print(people)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM