用对应于每个字符串的数字替换字典中的元组值(字符串)?
Replace tuple values (strings) in dictionary with a number that corresponds to each string?
我有一个看起来像这样的字典,其中的值是字符串元组,对应于一些浮点数:
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}
现在我要做的是用 second_dict 中的值(数字索引)替换 first_dict 中的元组。所以我最终应该得到:
final_dict = {(0, 1): 3.6, (0, 2): 7.0, (0, 3): 1.3}
这背后的想法是可以将到达元组作为矩阵中的 row/column 输入。
我知道元组是不可变的,所以我需要创建一个新的字典来执行此操作。最初我认为我可以遍历 first_dict 中的元组,然后将它们匹配到 second_dict,然后使用这些匹配创建一个 third_dict。然而,这似乎是不必要的,因为字典的全部意义在于不必 loop/iterate 覆盖它们。
你可以使用字典理解:
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()}
输出:
{(0, 1): 3.6, (0, 2): 7.0, (0, 3): 1.3}
使用字典理解
例如:
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)
输出:
{(0, 1): 3.6, (0, 2): 7.0, (0, 3): 1.3}
这里
final_dict = {(second_dict[k[0]], second_dict[k[1]]): v for k, v in first_dict.items()}
print(final_dict)
输出
{(0, 1): 3.6, (0, 2): 7.0, (0, 3): 1.3}
我有一个看起来像这样的字典,其中的值是字符串元组,对应于一些浮点数:
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}
现在我要做的是用 second_dict 中的值(数字索引)替换 first_dict 中的元组。所以我最终应该得到:
final_dict = {(0, 1): 3.6, (0, 2): 7.0, (0, 3): 1.3}
这背后的想法是可以将到达元组作为矩阵中的 row/column 输入。
我知道元组是不可变的,所以我需要创建一个新的字典来执行此操作。最初我认为我可以遍历 first_dict 中的元组,然后将它们匹配到 second_dict,然后使用这些匹配创建一个 third_dict。然而,这似乎是不必要的,因为字典的全部意义在于不必 loop/iterate 覆盖它们。
你可以使用字典理解:
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()}
输出:
{(0, 1): 3.6, (0, 2): 7.0, (0, 3): 1.3}
使用字典理解
例如:
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)
输出:
{(0, 1): 3.6, (0, 2): 7.0, (0, 3): 1.3}
这里
final_dict = {(second_dict[k[0]], second_dict[k[1]]): v for k, v in first_dict.items()}
print(final_dict)
输出
{(0, 1): 3.6, (0, 2): 7.0, (0, 3): 1.3}