【问题标题】:Replace tuple values (strings) in dictionary with a number that corresponds to each string?用与每个字符串对应的数字替换字典中的元组值(字符串)?
【发布时间】:2019-11-14 11:08:28
【问题描述】:

我有一个看起来像这样的字典,其中的值是字符串元组,对应于一些浮点数:

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}

这背后的想法是可以将到达元组作为矩阵中的行/列输入。

我知道元组是不可变的,所以我需要创建一个新的 dict 来执行此操作。最初我认为我可以遍历 first_dict 中的元组,然后将它们匹配到 second_dict,然后使用这些匹配项创建一个 third_dict。但是,这似乎没有必要,因为 dicts 的全部意义在于不必循环/迭代它们。

【问题讨论】:

  • 你必须迭代

标签: python dictionary tuples key key-value-store


【解决方案1】:

您可以使用字典理解:

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}

【讨论】:

    【解决方案2】:

    使用字典理解

    例如:

    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}
    

    【讨论】:

      【解决方案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}
      

      【讨论】:

      • 使用解包更干净:{(second_dict[j], second_dict[k]): v for (j, k), v in first_dict.items()}
      猜你喜欢
      • 2011-04-13
      • 2017-07-15
      • 2018-09-11
      • 1970-01-01
      • 2022-01-15
      • 1970-01-01
      • 2013-11-18
      • 2012-02-18
      • 2023-04-04
      相关资源
      最近更新 更多