提供了字典:
entries = {'blue': ' the color of the sky', 'coffee': ' fuel for programmers'}
如何将密钥附加到列表中?
我到这为止了
results = []
for entry in entries:
results.append(entry[?])
答案 0 :(得分:3)
您可以使用.keys()访问字典的键。您可以使用list()将其转换为列表。例如,
entries = {'blue': ' the color of the sky', 'coffee': ' fuel for programmers'}
keys = list(entries.keys())
答案 1 :(得分:1)
字典的键已经是一个类似于对象的列表。如果您真的想要一个列表,它很容易转换
>>> 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