【问题标题】:How can I get list of values from dict?如何从 dict 获取值列表?
【发布时间】:2013-04-20 03:27:53
【问题描述】:

如何在 Python 中获取 dict 中的值列表?

在 Java 中,将 Map 的值作为 List 获取就像 list = map.values(); 一样简单。我想知道 Python 中是否有类似的简单方法可以从字典中获取值列表。

【问题讨论】:

    标签: python list dictionary


    【解决方案1】:

    dict.values 返回字典值的view,因此您必须将其包装在list 中:

    list(d.values())
    

    【讨论】:

    • 或者,[d[k] for k in d] 同时适用于 python2.x 和 3.x(请注意,我实际上并不是建议您使用它)。通常您实际上并不需要值列表,所以d.values() 就可以了。
    • 稍微“更好”的链接(指向您发布的页面上的特定位置):docs.python.org/2/library/stdtypes.html#dict.values
    • d.itervalues() 用于返回字典值的迭代器并避免列表。
    • @figs 问题是“值列表”但是是的,如果您在 Python 2 上迭代字典,肯定使用 d.itervalues(),在大多数情况下,您只需要迭代并且不需要列表.
    【解决方案2】:

    你可以使用* operator来解压dict_values:

    >>> d = {1: "a", 2: "b"}
    >>> [*d.values()]
    ['a', 'b']
    

    或列表对象

    >>> d = {1: "a", 2: "b"}
    >>> list(d.values())
    ['a', 'b']
    

    【讨论】:

      【解决方案3】:

      应该有一种——最好只有一种——明显的方法。

      因此list(dictionary.values())一种方式

      然而,考虑到 Python3,什么更快?

      [*L][].extend(L)list(L)

      small_ds = {x: str(x+42) for x in range(10)}
      small_df = {x: float(x+42) for x in range(10)}
      
      print('Small Dict(str)')
      %timeit [*small_ds.values()]
      %timeit [].extend(small_ds.values())
      %timeit list(small_ds.values())
      
      print('Small Dict(float)')
      %timeit [*small_df.values()]
      %timeit [].extend(small_df.values())
      %timeit list(small_df.values())
      
      big_ds = {x: str(x+42) for x in range(1000000)}
      big_df = {x: float(x+42) for x in range(1000000)}
      
      print('Big Dict(str)')
      %timeit [*big_ds.values()]
      %timeit [].extend(big_ds.values())
      %timeit list(big_ds.values())
      
      print('Big Dict(float)')
      %timeit [*big_df.values()]
      %timeit [].extend(big_df.values())
      %timeit list(big_df.values())
      
      Small Dict(str)
      256 ns ± 3.37 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
      338 ns ± 0.807 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
      336 ns ± 1.9 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
      
      Small Dict(float)
      268 ns ± 0.297 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
      343 ns ± 15.2 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
      336 ns ± 0.68 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
      
      Big Dict(str)
      17.5 ms ± 142 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
      16.5 ms ± 338 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
      16.2 ms ± 19.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
      
      Big Dict(float)
      13.2 ms ± 41 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
      13.1 ms ± 919 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
      12.8 ms ± 578 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
      

      在 Intel(R) Core(TM) i7-8650U CPU @ 1.90GHz 上完成。

      # Name                    Version                   Build
      ipython                   7.5.0            py37h24bf2e0_0
      

      结果

      1. 对于小型词典,* operator 更快
      2. 对于重要的大型词典,list() 可能会稍微快一些

      【讨论】:

      • list(L), cuz “应该有一种——最好只有一种——明显的方法。”
      • 按建议更改,@Ufos
      【解决方案4】:

      按照以下示例进行操作--

      songs = [
      {"title": "happy birthday", "playcount": 4},
      {"title": "AC/DC", "playcount": 2},
      {"title": "Billie Jean", "playcount": 6},
      {"title": "Human Touch", "playcount": 3}
      ]
      
      print("====================")
      print(f'Songs --> {songs} \n')
      title = list(map(lambda x : x['title'], songs))
      print(f'Print Title --> {title}')
      
      playcount = list(map(lambda x : x['playcount'], songs))
      print(f'Print Playcount --> {playcount}')
      print (f'Print Sorted playcount --> {sorted(playcount)}')
      
      # Aliter -
      print(sorted(list(map(lambda x: x['playcount'],songs))))
      

      【讨论】:

      • 正是我想要的!
      【解决方案5】:
      out: dict_values([{1:a, 2:b}])
      
      in:  str(dict.values())[14:-3]    
      out: 1:a, 2:b
      

      纯粹出于视觉目的。不会产生有用的产品...仅当您希望以段落类型的形式打印长字典时才有用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-11-17
        • 1970-01-01
        • 2019-02-18
        • 1970-01-01
        • 2014-02-12
        • 1970-01-01
        • 2013-07-20
        相关资源
        最近更新 更多