0

given a dictionary:

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

how do I append the keys into a list?

I got this far:

results = []
for entry in entries:
    results.append(entry[?])
Rajat Mishra
  • 3,635
  • 4
  • 27
  • 41
jay
  • 11
  • 1
  • remove the `[?]`. should be enough. but quicker just to do `list(entries)` – joel Apr 26 '20 at 22:53
  • 1
    Does this answer your question? [How to return dictionary keys as a list in Python?](https://stackoverflow.com/questions/16819222/how-to-return-dictionary-keys-as-a-list-in-python) – joel Apr 26 '20 at 22:54

2 Answers2

4

You can access the keys of a dictionary with .keys(). You can turn that into a list with list(). For example,

entries = {'blue': ' the color of the sky', 'coffee': ' fuel for programmers'}
keys    = list(entries.keys())
Bobby Ocean
  • 3,120
  • 1
  • 8
  • 15
1

The keys of the dict is already a list like object. If you really want a list, its easy to convert

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

If you want to add the keys to an existing list

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

You can frequently just use the dict object

>>> entries.keys()
dict_keys(['blue', 'coffee'])
>>> 'blue' in entries
True
>>> for key in entries:
...     print(key)
... 
blue
coffee
tdelaney
  • 73,364
  • 6
  • 83
  • 116