简体   繁体   中英

How replace keys of a dictionary with keys of another dictionary?

I have two dictionaries dict1 and dict2. I want to replace the keys of dict1 with keys of dict2. dict1.keys() is as follows:

dict_keys(['8014.png54523', '7595.png37735', '6659.png50805', '8058.png26143','05324.png31372'])

dict2.keys() is as follows:

dict_keys(['8014.png671302', '7595.png567733', '6659.png681968', '8058.png442154', '05324.png530138'])

I want dict2.keys() as dict1.keys. Can anyone help me out.

Thanks!

Code

new_dict = {k2:dict1[k1] for k1, k2 in zip(dict1.keys(), dict2.keys())}

Test

Keys & dummy values

keys1 = ['8014.png54523', '7595.png37735', '6659.png50805', '8058.png26143','05324.png31372']
vals1 = list(range(len(keys1)))
keys2 = ['8014.png671302', '7595.png567733', '6659.png681968', '8058.png442154', '05324.png530138']
vals2 = list(range(len(keys1)))

Dictionaries

dict1 = dict(zip(keys1, vals1))
dict2 = dict(zip(keys2, vals2))

New Dictionary

# Have each k1, v1 in dict1
# and       k2, v2 from dict2
# new dict uses k2:v1
# where v1 = dict1[k1]
new_dict = {k2:dict1[k1] for k1, k2 in zip(dict1.keys(), dict2.keys())}

print(new_dict)

Output

{'8014.png671302': 0, '7595.png567733': 1, '6659.png681968': 2, '8058.png442154': 3, '05324.png530138': 4}

你可以试试这个:

new_dict1 = {new_key: dict1[old_key] for old_key, new_key in zip(dict1.keys(), dict2.keys())}

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