user984003
user984003

Reputation: 29557

Convert dictionary to list of values, sorted by keys

I have a dictionary

d = {
     date_3:  val_3,
     date_1:  val_1,
     date_2:  val_2,
}

I want to convert this to a list, sorted by the dictionary keys:

l = [val_1,
     val_2,
     val_3
]

How do I do that?

Upvotes: 1

Views: 671

Answers (4)

Nishant Nawarkhede
Nishant Nawarkhede

Reputation: 8400

You can do it as ,

[i[1] for i in sorted(d.items(), key=lambda s: s[0])]

Upvotes: 0

Vijay Kumar
Vijay Kumar

Reputation: 345

this will help you

l = sorted(d.keys())
l = [d[u] for u in l]
print l

Upvotes: 1

Neel
Neel

Reputation: 21243

you will get values using dict.keys() and you can sort it using list.sort()

values = d.keys()
values.sort()
[d[x] for x in values]

Upvotes: 0

Ikke
Ikke

Reputation: 101231

This will give you a list of values, sorted by key.

l = [d[k] for k in sorted(d)]

Upvotes: 5

Related Questions