0

Why does myDictionary.values() return a dict_values object as opposed to a set or list or tuple?

I don't see the advantage to the dict_values type and it causes issues when casting to other types, e.g.:

>>> np.array( {0: 0, 1: 1}.values() )
array(dict_values([0, 1]), dtype=object)
>>> np.array( list( {0: 0, 1: 1}.values() ) )
array([0, 1])

Why did Python's .values() go from using the more-compatible lists in Python 2 to returning its own custom object in Python 3?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Zaz
  • 46,476
  • 14
  • 84
  • 101
  • 1
    `dict.values` runs on O(1) time, rather than O(n) time, without *forcing* you into its choice of data type. – chepner Jul 05 '22 at 22:55
  • So couldn't they just return a `generator`? Are there any other advantages? – Zaz Jul 05 '22 at 22:58
  • This is part of a broader change in 3.x from lists to more memory-efficient types: https://docs.python.org/3/whatsnew/3.0.html#views-and-iterators-instead-of-lists. You can read more about it in [the relevant PEP](https://peps.python.org/pep-3106/). – jonrsharpe Jul 05 '22 at 23:00
  • And also, if that is the case, how can I avoid iterating over it twice with `np.array( list( ...` ? – Zaz Jul 05 '22 at 23:00
  • `generator` is just the type of object returned by a function defined by a `def` statement that uses `yield` statements; it's not an all-purpose iterator. – chepner Jul 05 '22 at 23:01

1 Answers1

1

There are several advantages:

  1. dict.values runs in O(1) time, not O(n).

  2. dict.values lets you choose if you want a set or a list or a tuple, etc, rather than picking the container for you.

  3. dict.values returns an iterable which provides an iterator that that reflects the current values of the dict, not the values present when you called dict.values. For example:

    >>> d = dict(a=1, b=2)
    >>> dv = d.values()
    >>> list(dv)
    [1, 2]
    >>> d['c'] = 3
    >>> list(dv)
    [1,2,3]
    

    Note that we didn't have to call d.values() again for list(dv) to pick up the newly added value.

chepner
  • 497,756
  • 71
  • 530
  • 681