Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 733
PKL Avatar asked Mar 24 '26 14:03

PKL


2 Answers

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]
like image 192
Benjamin Rowell Avatar answered Mar 26 '26 03:03

Benjamin Rowell


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]
    
like image 45
Serge Ballesta Avatar answered Mar 26 '26 03:03

Serge Ballesta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!