Вопрос

I have an object like this:

t = {'rand_key_1': ['x'], 'rand_key_2': [13,23], 'rand_key_3': [(1)], 'rk5': [1,100,3,4,3,3]}

a dictionary with random keys (string and/or int) which ALL have a list as a value, with varying sizes.

I want to turn this dictionary into an OrderedDict which is ordered depending on the Length of the list of the dictionary items. So after ordering I want to get:

t_ordered = {'rk5': ..., 'rand_key_2': .., 'rand_key_1': .., 'rand_key_3': ..}

(if two or more items have same value, their order do not really matter.

I tried this but I am failing:

OrderedDict(sorted(d, key=lambda t: len(t[1])))

I am not experiences so excuse me if what I try is uber stupid.

What can I do?

Thank you.

Это было полезно?

Решение

You were actually very close with the sorting function you passed to sorted. The thing to note is that sorted will return an interable of the dictionaries keys in order. So if we fix your function to index the dictionary with each key:

>>> sorted(t, key=lambda k: len(t[k]))
['rand_key_3', 'rand_key_1', 'rand_key_2', 'rk5']

You can also specify that the keys are returned in reverse order and iterating directly over these keys:

>>> for sorted_key in sorted(t, key=lambda k: len(t[k]), reverse=True):
...     print sorted_key, t[sorted_key]

rk5 [1, 100, 3, 4, 3, 3]
rand_key_2 [13, 23]
rand_key_3 [1]
rand_key_1 ['x']

Usually you wouldn't need to create an OrderedDict, as you would just iterate over a new sorted list using the latest dictionary data.

Другие советы

Using simple dictionary sorting first and then using OrderedDict():

>>> from collections import OrderedDict as od
>>> k=sorted(t, key=lambda x:len(t[x]), reverse=True)
>>> k
['rk5', 'rand_key_2', 'rand_key_3', 'rand_key_1']

>>> od((x, t[x]) for x in k)
OrderedDict([('rk5', [1, 100, 3, 4, 3, 3]), ('rand_key_2', [13, 23]), ('rand_key_3', [1]), ('rand_key_1', ['x'])])

Since an ordered dictionary remembers its insertion order, so you can do this:

OrderedDict(sorted(d.items(), key=lambda t: len(t[0])))

OrderedDict in Python is a collection that remembers the order in which items were inserted. Ordered in this context does not mean sorted.

If all you need is to get all the items in sorted order you can do something like this:

for key, value in sorted(t, key = lambda x: -len(x[0])):
  # do something with key and value

However, you are still using an unsorted data structure - just iterating over it in sorted order. This still does not support operations like looking up the k-th element, or the successor or predecessor of an element in the dict.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top