-1

I would like to retrieve dictionary keys according to a list of priority keys. The dictionary looks like:

My_dic = {'name': 'John', 'age': '33', 'gender':'male', 'car': 'SUV'}

And the list of criteria is:

My_criteria = ['gender', 'age', 'car', 'name']

How can this be done in a pythonic way?

Empario
  • 402
  • 6
  • 19
  • 2
    Python dictionaries cannot be sorted. Sorting the *display* of them is possible though. See https://stackoverflow.com/questions/9001509/how-can-i-sort-a-dictionary-by-key –  Aug 03 '16 at 18:59
  • I like to use [operator module functions](https://docs.python.org/3/howto/sorting.html#operator-module-functions) for the key function. – wwii Aug 03 '16 at 19:02
  • @Jeffrey: Thanks for the quick reply. If I use OrderedDict, how would I order it by my list? – Empario Aug 03 '16 at 19:02
  • @Empario see my answer below to use an OrderedDict. – Julien Spronck Aug 03 '16 at 19:12

4 Answers4

1

you can retrieve elements by the order you specified

for k in sorted(My_dic, key=My_criteria.index):
    print(k,":",My_dic.get(k))
karakfa
  • 66,216
  • 7
  • 41
  • 56
1

You could use an OrderedDict:

from collections import OrderedDict

My_dic = {'name': 'John', 'age': '33', 'gender':'male', 'car': 'SUV'}
My_criteria = ['gender', 'age', 'car', 'name']

My_dic = OrderedDict([(x, My_dic[x]) for x in My_criteria])
# OrderedDict([('gender', 'male'),
#              ('age', '33'),
#              ('car', 'SUV'),
#              ('name', 'John')])

The advantage is that you can still access your data as if it was a dictionary (e.g. My_dic['age']).

Julien Spronck
  • 15,069
  • 4
  • 47
  • 55
0

Dictionaries are not sortable, due to the way the information is stored (http://www.python-course.eu/dictionaries.php).

You could create a new list of tuple values using list comprehension, like:

ordered_info = [(i,my_dic[i]) for i in my_criteria]

crld
  • 387
  • 3
  • 9
0

Just iterate through your priority keys, not your dict, then get values using those keys:

for key in My_criteria:
    print My_dic[key]

will print the values of your keys in the order that My_criteria is in.

R Nar
  • 5,465
  • 1
  • 16
  • 32