PKL
PKL

Reputation: 55

Sorting Values in Python Dictionaries

I am a newbie to Python and not fully sure how to work with dictionaries. I want to sort one of the dictionaries with another one. So I have something like given below. Each of the vertex features is a list.

vertex_features = ['Charge', 'Time', 'TimeDelta', 'TimeSinceLastPulse']
..........
..........
a = {feature : [] for feature in vertex_features }

I want to sort the Time feature (and get the corresponding Charge, Time Delta etc.), which I did by

hit_order = np.argsort(features['Time'])

However when I try

for feature in features:
    features[feature] = features[feature][hit_order]

It gives the error

TypeError: only integer scalar arrays can be converted to a scalar index

I have also tried

for feature in features:
    features[feature] = features[feature][for i in hit_order]

But unable to get the sorted lists. I am not fully sure if I understand what I am doing wrong with the sorting here. Help is very much appreciated.

Upvotes: 3

Views: 129

Answers (2)

Serge Ballesta
Serge Ballesta

Reputation: 148890

A numpy ndarray and a Python list are different animals. They can be trivially converted back and forth, but only a ndarray can accept another ndarray as index. For Python lists, the idiomatic way is to use a comprehension.

As features contains plain lists you must choose one way:

  1. convert to numpy array:

    for feature in features:
        features[feature] = np.array(features[feature])[hit_order]
    
  2. build a list with a comprehension:

    for feature in features:
        features[feature] = [features[feature][i] for i in hit_order]
    

Upvotes: 1

Benjamin Rowell
Benjamin Rowell

Reputation: 1411

The problem you've come across is Python Lists don't support reording via the square bracket syntax. This is a feature of Numpy Arrays.

When you use square brackets on a Python List, the interpreter is either expecting a scalar index or some kind of slice.

Instead of using a List, you can wrap the feature list returned from the dict in np.array as below:

import numpy as np

vertex_features = ['Charge', 'Time', 'TimeDelta', 'TimeSinceLastPulse']
features = {feature: [] for feature in vertex_features}

hit_order = np.argsort(features['Time'])

for feature in features:
    features[feature] = np.array(features[feature])[hit_order]

Or when you declare your dict comprehension, wrap the list:

import numpy as np

vertex_features = ['Charge', 'Time', 'TimeDelta', 'TimeSinceLastPulse']
features = {feature: np.array([]) for feature in vertex_features}

hit_order = np.argsort(features['Time'])

for feature in features:
    features[feature] = features[feature][hit_order]

Upvotes: 2

Related Questions