question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Make it possible to initialize array from dictionary values in Python 3

See original GitHub issue

At the moment arrays can’t be initialized from dictionary values in Python 3:

In [1]: import numpy as np

In [2]: d = {'a':1,'b':2,'c':3}

In [3]: np.array(d.values())
Out[3]: array(dict_values([2, 1, 3]), dtype=object)

and one has to instead explicitly convert to a list first:

In [4]: np.array(list(d.values()))
Out[4]: array([2, 1, 3])

It might be worth adding a special case in the initializer for the array to automatically do this conversion, since d.values() is a valid iterator?

Issue Analytics

  • State:open
  • Created 8 years ago
  • Reactions:2
  • Comments:7 (7 by maintainers)

github_iconTop GitHub Comments

3reactions
njsmithcommented, Mar 25, 2015

No, in python 3, dict.keys and dict.values (and also dict.items for that matter) don’t return iterators, they return special magical view classes. Which are iterable, of course, but they also have specific documented types.

I too am dubious about np.array accepting arbitrary iterables (because of memory overhead and the difficulty of even recognizing an iterable when you see one), but I’m +0.7 on teaching np.array to treat the dict views the same way we treat lists. On Mar 25, 2015 9:39 AM, “Jaime” notifications@github.com wrote:

I don’t think that array has a way of knowing that what it received is a dict.keys() or dict.values() iterator. Any change would require accepting generic iterators, which is not an easy task, e.g. np.fromiter requires an explicit dtype, while np.array can figure it out from the input. So I don’t really see an easy way of making this happen…

— Reply to this email directly or view it on GitHub https://github.com/numpy/numpy/issues/5718#issuecomment-86110018.

1reaction
eric-wiesercommented, Apr 11, 2017

What is actually going on here?

This works fine:

class A(object):
    def __getitem__(self, index):
        if index > 3:
            raise IndexError
        return index

    def __len__(self): return 4

np.array(A())  # array([1, 2, 3, 4])

So why does np.array(dict_keys) not?

Edit: Duh, because dict_keys, despite having a __len__, has no __getitem__

Read more comments on GitHub >

github_iconTop Results From Across the Web

python - Can I create a numpy array of dictionary values from ...
You could do this with a structured array and np.in1d . import numpy as np d = {'a': 1, 'b': 2, 'c': 3,...
Read more >
Python | Initializing dictionary with empty lists - GeeksforGeeks
Method #1: Using Dictionary comprehension: This is the most sought method to do this initialization. In this method, we create the no. of...
Read more >
How to Convert Dictionary Values to a List in Python
In Python, a dictionary is a built-in data type that can be used to store data in a way thats different from lists...
Read more >
Collection Types - Swift.org
If you create an array, a set, or a dictionary, and assign it to a variable, the collection that's created will be mutable....
Read more >
Dictionaries in Python - Real Python
First, a given key can appear in a dictionary only once. Duplicate keys are not allowed. A dictionary maps each key to a...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found