0

I'm trying to build a matrix that will contains the values from a dictionary, I know dictionaries are unordered but I'd like to sort the values in the matrix (which can be sorted) in a certain order based off the key names in the dictionary.

Let's say I have a dictionary like so:

{'a': 1, 'b': 2, 'c': 3 } 

And a list with the key names in the order that I'd like the data from the matrix to be arranged:

['b', 'c'. 'a']

How can I use the list above to sort the values from the dictonary in a way that gives me a list like so:

[2, 3, 1]

Without explicitly mentioning each key during list comprehension, like so:

data = [ data['b'], data['c'], data['a'] for data in dict ] 

The dictionary that I'm pulling data from has many keys and I'd rather not use the above method to pull 10-15 data points from this dictionary.

Felipe Rios
  • 101
  • 2
  • 10
  • I don't know what your 'matrix' is other than that it's some ordered data structure to take you at your word, but if you loop over `['b', 'c', 'a']` (normal `for`) and add to your matrix in that order, mission accomplished presumably. – Two-Bit Alchemist Oct 21 '15 at 20:58
  • `[d[key] for key in ['b', 'c', 'a']]` – Peter Wood Oct 21 '15 at 20:58

2 Answers2

1

I'm not sure what you are doing with that comprehension, but consider:

In [1]: dict = {'a': 1, 'b': 2, 'c': 3 } 

In [2]: keys = ['b', 'c', 'a']

In [3]: [dict[key] for key in keys]
Out[3]: [2, 3, 1]
user2085282
  • 1,077
  • 1
  • 8
  • 16
1

I'm a big fan of python's functional abilities. Here would be one cool way to use them:

d = {'a': 1, 'b': 2, 'c': 3 }
print map(lambda x: d[x], ['b', 'c', 'a'])

This should give you your solution. What it does is takes each element of the array that you wanted and maps it to the corresponding value in the dictionary. (Basically it does what you mentioned in a functional manner)

Hope it helps!

Almog
  • 731
  • 4
  • 10
  • I think list comprehensions are more efficient (and of course clearer), e.g. `[d[k] for k in keys]` – Tom Karzes Oct 21 '15 at 21:04
  • Actually I think @TomKarzes is right: http://stackoverflow.com/questions/1247486/python-list-comprehension-vs-map but only because my answer has a lambda in it :) – Almog Oct 21 '15 at 21:08
  • @LetzerWille I'm highly skeptical at least in the general case. Comprehensions are built-in syntax and can be optimized by the 'compiler'. The map there at least is less efficient if only because it has to create an anonymous function. – Two-Bit Alchemist Oct 21 '15 at 21:09