简体   繁体   中英

How to make a new dictionary from the values of (same lengths and same keys) two different dictionaries, using as key-value pair

Two dictionaries with the same keys and same length,

dict_val = {0: [0.2, 0.8], 1: [0.3125, 0.6875]}
dict_word = {0:['bank#0', 'rock#0'], 1:['bank#1', 'rock#1'] }

How to create a new dictionary using the values of the above two dictionaries as "word_val" below,

word_val = {bank#0 : 0.2, rock#0: 0.8, bank#1: 0.3125, rock#1: 0.687} 

note: values of one dictionary is using as keys and values of the other dictionary as values in the newly created dictionary.

You can use zip and a nested dict comprehension:

{k_: v_ for k in dict_val for k_, v_ in zip(dict_word[k], dict_val[k])}
# {'bank#0': 0.2, 'rock#0': 0.8, 'bank#1': 0.3125, 'rock#1': 0.6875}

You can use itertools.chain with zip :

>>> from itertools import chain
>>> dict(zip(chain(*dict_word.values()), chain(*dict_val.values())))
{'bank#0': 0.2, 'rock#0': 0.8, 'bank#1': 0.3125, 'rock#1': 0.6875}

Python 3.6+ onwards, dicts are guaranteed to maintain insertion order, so if you are using 3.6+, this solution is safe.

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