【问题标题】:How to combine 2 lists into 1 dictionary using a function [duplicate]如何使用函数将2个列表组合成1个字典[重复]
【发布时间】:2020-09-22 23:31:46
【问题描述】:

这是我尝试使用的 2 个列表:

names = ['joe', 'tom', 'barb', 'sue', 'sally']
scores = [10, 23, 13, 18, 12]

我正在使用我创建的名为 makeDictionary 的函数,其参数为 (list1, list2)

我不想要代码中的直接答案,但是如何让names 列出字典中的键,而scores 列出字典中的值?

示例输出字典:

{'joe': 10, 'tom': 23, 'barb': 13, 'sue': 18, 'sally': 12}

【问题讨论】:

    标签: python list function dictionary


    【解决方案1】:

    这就是zip 的用途:

    >>> dict(zip(names, scores))
    {'joe': 10, 'tom': 23, 'barb': 13, 'sue': 18, 'sally': 12}
    

    【讨论】:

      【解决方案2】:

      你可以这样做:

      dict(zip(names,scores))
      

      输出

      {'joe': 10, 'tom': 23, 'barb': 13, 'sue': 18, 'sally': 12}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-05-20
        • 1970-01-01
        • 2019-07-03
        • 1970-01-01
        • 1970-01-01
        • 2016-03-13
        • 2018-11-14
        相关资源
        最近更新 更多