You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python实现双元组转字典函数 首元组为键次元组为对应值

问题需求

编写接收两个元组作为入参的函数,返回字典类型结果,规则如下:

  • 字典的键取自第一个元组的元素,对应值为第二个元组相同位置的元素
  • 第一个元组内如果有重复键,仅保留首次出现的键值映射
  • 调用示例:输入tuples_to_dict(('a','b', 'c', 'a'), (1,2,3,4)),需返回{'a':1, 'b':2, 'c':3}
实现代码
def tuples_to_dict(keys_tuple: tuple, values_tuple: tuple) -> dict:
    res = {}
    # 取两个元组的最小长度遍历,避免索引越界
    for i in range(min(len(keys_tuple), len(values_tuple))):
        current_key = keys_tuple[i]
        # 键不存在时才写入,保证首次出现的映射不被覆盖
        if current_key not in res:
            res[current_key] = values_tuple[i]
    return res
效果验证

执行测试代码:

if __name__ == "__main__":
    test_res = tuples_to_dict(('a','b', 'c', 'a'), (1,2,3,4))
    print(test_res)

运行输出:
{'a': 1, 'b': 2, 'c': 3}

避坑提示:不要直接使用dict(zip(keys_tuple, values_tuple))实现,该写法会让位置靠后的重复键覆盖之前的同键值,上述测试用例用该写法会得到错误结果{'a': 4, 'b': 2, 'c': 3}。

内容的提问来源于stack exchange,提问作者directyou

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 04:27:21