Pandasncode
Pandasncode

Reputation: 27

Sorting arrays within a dictionary

The information inside the arrays is in the "reverse" order of how I want it. Ideally it could be sorted by the dates within the array but I'm 100% certain just reversing the order would work. By using something like this:

sorted(Dictionary[self], key=lambda i: i[1][0], reverse=True)

I know that the above JUST sorts the arrays themselves into reverse order and not the data inside the array into reverse order. With the Dictionary like this (all items are a file name)

Dictionary = {'a':[XPJulianDay(Timefurthestinpastfromnow), ... XPJulianDay(timeclosest2currnttime)], 'b':[RQJulianDay(Timefurthestinpastfromnow), ... RQJulianDay(timeclosest2currnttime)], 'c':[WSJulianDay(Timefurthestinpastfromnow), ... WSJulianDay(timeclosest2currnttime)] ..... (9 different ones total) }

turning into this

Dictionary = {'a':[XPJulianDay(timeclosest2currnttime), ... XPJulianDay(Timefurthestinpastfromnow)], 'b':[RQJulianDay(timeclosest2currnttime), ... RQJulianDay(Timefurthestinpastfromnow)], 'c':[WSJulianDay(timeclosest2currnttime), ... WSJulianDay(Timefurthestinpastfromnow)] .... }

Upvotes: 0

Views: 95

Answers (2)

Jab
Jab

Reputation: 27505

You can use the dict comprehension as stated by @mguijarr or use dict and zip

Dictionary = dict(zip(Dictionary, map(sorted, Dictionary.values()))))

But if your keys really are just the 'a', 'b', ... then why are you using a dict? Just use a list...

Upvotes: 0

mguijarr
mguijarr

Reputation: 7920

You can try that:

Dictionary.update({ k: sorted(v) for k, v in Dictionary.items() })

It updates the dictionary with its own keys, with sorted values.

Example:

>>> Dictionary = {"a": [7,6,1,2], "b": [8,0,2,5] }
>>> Dictionary.update({ k: sorted(v) for k, v in Dictionary.items() })
>>> Dictionary
{'a': [1, 2, 6, 7], 'b': [0, 2, 5, 8]}
>>> 

Note that a new dictionary is created for the call to .update() using a dict comprehension.

If needed you can replace sorted() by reversed() ; but reversed() returns an iterator so if you want a list you need to call it with list() (it is better to keep the iterator if you can).

Example with reversed:

>>> Dictionary = {"a": [7,6,1,2], "b": [8,0,2,5] } ; Dictionary.update({ k: reversed(v) for k, v in Dictionary.items() })
>>> Dictionary
{'a': <list_reverseiterator object at 0x7f537a0b3a10>, 'b': <list_reverseiterator object at 0x7f537a0b39d0>}
>>>

Upvotes: 2

Related Questions