Make it possible to initialize array from dictionary values in Python 3
See original GitHub issueAt 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:
- Created 8 years ago
- Reactions:2
- Comments:7 (7 by maintainers)
Top 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 >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
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:
What is actually going on here?
This works fine:
So why does
np.array(dict_keys)
not?Edit: Duh, because
dict_keys
, despite having a__len__
, has no__getitem__