【问题标题】:how to append dictionary keys into a list? [duplicate]如何将字典键附加到列表中? [复制]
【发布时间】:2020-08-10 10:25:24
【问题描述】:

给定一本字典:

entries = {'blue': ' the color of the sky', 'coffee': ' fuel for programmers'}

如何将键附加到列表中?

我已经走到这一步了:

results = []
for entry in entries:
    results.append(entry[?])

【问题讨论】:

标签: python python-3.x


【解决方案1】:

您可以使用 .keys() 访问字典的键。你可以用 list() 把它变成一个列表。例如,

entries = {'blue': ' the color of the sky', 'coffee': ' fuel for programmers'}
keys    = list(entries.keys())

【讨论】:

    【解决方案2】:

    dict 的键已经是一个类似对象的列表。如果你真的想要一个列表,它很容易转换

    >>> entries = {'blue': ' the color of the sky', 'coffee': ' fuel for programmers'}
    >>> l = list(entries)
    >>> l
    ['blue', 'coffee']
    

    如果您想将键添加到现有列表中

    >>> mylist = [1,2,3]
    >>> mylist += entries
    >>> mylist
    [1, 2, 3, 'blue', 'coffee']
    

    你可以经常只使用 dict 对象

    >>> entries.keys()
    dict_keys(['blue', 'coffee'])
    >>> 'blue' in entries
    True
    >>> for key in entries:
    ...     print(key)
    ... 
    blue
    coffee
    

    【讨论】:

      猜你喜欢
      • 2020-04-09
      • 2022-01-06
      • 2018-03-31
      • 2020-12-06
      • 2022-12-17
      • 1970-01-01
      • 2015-07-03
      • 2019-09-20
      • 1970-01-01
      相关资源
      最近更新 更多