0

I want to extract the values from a dictionary and print them as a list. For example: If i have letter = {"i": 3, "o": 2, "u": 2}

and want to extract 3,2, and 2 and print it as a list

[3, 2, 2] How do I do this? I've tried

print([x[::] for x in letter])

However, this prints out ['i', 'o', 'u'] and not [3, 2, 2]. Thank you for the help in advanced :)

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271

3 Answers3

3

There is a method in Python called .keys() that allows you to get the keys from a dict. Similarly, there is also a method called values() for the converse.

These are dict instance methods, ie:

myDict = { "i": 0, "t": 1, "f": 2 }
print(myDict.values())
ComedicChimera
  • 466
  • 1
  • 4
  • 15
0

You can just call dict.values() Further details here

Zooby
  • 325
  • 1
  • 7
  • when I use dict.values(letter) it returns dict_values([3, 2, 2]) however i want it to just return [3, 2, 2]. How do i do this? – The Bounty Hunter Nov 30 '17 at 04:21
  • 1
    list(dict.values()) – Zooby Nov 30 '17 at 04:22
  • 1
    @Zooby: If you're using a recent version of Python you can also do `[*letter.values()]`. Bear in mind that a plain `dict` is an unordered collection, so the ordering of the values list may not be what you expect it to be. – PM 2Ring Nov 30 '17 at 04:31
0

Try letter.values(), which gives you dict_values([3, 2, 2])

>>> letter = {"i": 3, "o": 2, "u": 2}
>>> print(list(letter.values()))
[3, 2, 2]
srikavineehari
  • 2,502
  • 1
  • 11
  • 21