0

I'm trying to get values from my dictionary here

for elem in set(sample_txt):

       d = {elem:sample_txt.count(elem)}

print(d.values())

d.values() should return a list of values:

The methods dict. keys() and dict. values() return lists of the keys or values explicitly. There's also an items() which returns a list of (key, value) tuples, which is the most efficient way to examine all the key value data in the dictionary. from developers.google.com

So I should get something like ['a', 'b', 'etc']. However in my example I get

type(d.values()) ---> <class 'dict_values'>

What's wrong?

feetwet
  • 3,248
  • 7
  • 46
  • 84
nachtblume
  • 57
  • 5
  • 1
    You're replacing `d` every time through the loop, not adding to it. So you'll only get the last value from the loop. Use `d[elem] = sample_txt.count(elem)` – Barmar Apr 12 '22 at 21:18
  • Ty @Barmar, that is also a mistake here. – nachtblume Apr 12 '22 at 21:22
  • Does this answer your question? [How can I get list of values from dict?](https://stackoverflow.com/questions/16228248/how-can-i-get-list-of-values-from-dict) – feetwet Apr 20 '23 at 23:16

2 Answers2

5

The quote you posted is related to python2, where indeed it returned list. In python3 you need to cast it by yourself list(d.values())

kosciej16
  • 6,294
  • 1
  • 18
  • 29
1

Given:

Python 3.10.2 (main, Feb  2 2022, 06:19:27) [Clang 13.0.0 (clang-1300.0.29.3)] on darwin

For Python 3, d.values() returns a dict_value object which is one of the dict view classes:

>>> txt='abcaaab'
>>> d={k:txt.count(k) for k in set(txt)}
>>> d
{'a': 4, 'c': 1, 'b': 2}
>>> d.values()
dict_values([4, 1, 2])

One of the neat things about dict views is the view is updated if the underlying dict changes:

>>> d
{'a': 4, 'c': 1, 'b': 2}
>>> v=d.values()
>>> v
dict_values([4, 1, 2])
>>> d['z']='live update!'
>>> v
dict_values([4, 1, 2, 'live update!'])

Depending on the version of Python, the representation may include the contents or may include only the class.

dawg
  • 98,345
  • 23
  • 131
  • 206