简体   繁体   中英

Replace tuple values (strings) in dictionary with a number that corresponds to each string?

I have a dict that looks something like this, where the values are string tuples, corresponding to some floating point number:

first_dict = {('item1', 'item2'): 3.6, ('item1', 'item3'): 7.0, ('item1', 'item4'): 1.3}

Then I have a second dict, where each item (part of the tuples in the first dict) is assigned a number:

second_dict = {'item1': 0, 'item2': 1, 'item3': 2, 'item4': 3, 'item5': 4}

Now what I want to do is replace the tuples in first_dict by its value (the number index) in second_dict. So I should end up with:

final_dict = {(0, 1): 3.6, (0, 2): 7.0, (0, 3): 1.3}

The idea behind this would then be that it's possible to enter reach tuple as a row/column in a matrix.

I know that tuples are immutable so I'd need to create a new dict to do this. Initially I thought I could iterate over the tuples in first_dict and then match them up to second_dict, and then create a third_dict using those matches. However, that seems unnecessary, as the whole point of dicts is to not have to loop/iterate over them.

You can use a dictionary comprehension:

first_dict = {('item1', 'item2'): 3.6, ('item1', 'item3'): 7.0, ('item1', 'item4'): 1.3}
second_dict = {'item1': 0, 'item2': 1, 'item3': 2, 'item4': 3, 'item5': 4}
final_dict = {tuple(second_dict[i] for i in a):b for a, b in first_dict.items()}

Output:

{(0, 1): 3.6, (0, 2): 7.0, (0, 3): 1.3}

Using a dictionary comprehension

Ex:

first_dict = {('item1', 'item2'): 3.6, ('item1', 'item3'): 7.0, ('item1', 'item4'): 1.3}
second_dict = {'item1': 0, 'item2': 1, 'item3': 2, 'item4': 3, 'item5': 4}

final_dict = {(second_dict.get(k[0]), second_dict.get(k[1])) :v for k, v in first_dict.items() }
print(final_dict)

Output:

{(0, 1): 3.6, (0, 2): 7.0, (0, 3): 1.3}

Here

final_dict = {(second_dict[k[0]], second_dict[k[1]]): v for k, v in first_dict.items()}
print(final_dict)

output

{(0, 1): 3.6, (0, 2): 7.0, (0, 3): 1.3}

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