Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dictionary keys and values to separate numpy arrays

I have a dictionary as

Samples = {5.207403005022627: 0.69973543384229719, 6.8970222167794759: 0.080782939731898179, 7.8338517407140973: 0.10308033284258854, 8.5301143255505334: 0.018640838362318335, 10.418899728838058: 0.14427355015329846, 5.3983946820220501: 0.51319796560976771} 

I want to separate the keys and values into 2 numpy arrays. I tried np.array(Samples.keys(),dtype=np.float) but i get an error TypeError: float() argument must be a string or a number

like image 362
VeilEclipse Avatar asked May 15 '14 03:05

VeilEclipse


People also ask

How do you print keys and values separately in Python?

Method 1: Split dictionary keys and values using inbuilt functions. Here, we will use the inbuilt function of Python that is . keys() function in Python, and . values() function in Python to get the keys and values into separate lists.

What is a correct method to split arrays NumPy?

Splitting NumPy Arrays Splitting is reverse operation of Joining. Joining merges multiple arrays into one and Splitting breaks one array into multiple. We use array_split() for splitting arrays, we pass it the array we want to split and the number of splits.


2 Answers

You can use np.fromiter to directly create numpy arrays from the dictionary key and values views:

In python 3:

keys = np.fromiter(Samples.keys(), dtype=float) vals = np.fromiter(Samples.values(), dtype=float) 

In python 2:

keys = np.fromiter(Samples.iterkeys(), dtype=float) vals = np.fromiter(Samples.itervalues(), dtype=float) 
like image 199
ankostis Avatar answered Sep 28 '22 16:09

ankostis


On python 3.4, the following simply works:

Samples = {5.207403005022627: 0.69973543384229719, 6.8970222167794759: 0.080782939731898179, 7.8338517407140973: 0.10308033284258854, 8.5301143255505334: 0.018640838362318335, 10.418899728838058: 0.14427355015329846, 5.3983946820220501: 0.51319796560976771}  keys = np.array(list(Samples.keys())) values = np.array(list(Samples.values())) 

The reason np.array(Samples.values()) doesn't give what you expect in Python 3 is that in Python 3, the values() method of a dict returns an iterable view, whereas in Python 2, it returns an actual list of the keys.

keys = np.array(list(Samples.keys())) will actually work in Python 2.7 as well, and will make your code more version agnostic. But the extra call to list() will slow it down marginally.

like image 42
piggs_boson Avatar answered Sep 28 '22 14:09

piggs_boson