如何将字典键附加到列表中?

2024-06-28 10:10:52 发布

您现在位置:Python中文网/ 问答频道 /正文

给一本字典:

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

如何将键附加到列表中

我走了这么远:

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

Tags: ofthe列表for字典blueresultscolor
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

您可以使用.keys()访问字典的键。可以使用list()将其转换为列表。比如说,

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

相关问题 更多 >