0

I have a dictionary that looks like:

myDict = { "age":value1,"size":value2,'weigth':value3 ... }

And I simply want to get a list of values from this dictionary BUT in some order defined by a list:

order_list = ["age","weigth","size", ... ]

So the result will be:

result_list = [value1,value3,value2, ... ]

The simplest way is to iterate through the order_list this way:

for key in order_list:
    result_list.append(myDict[key])

But I beleive that there is a more efficient and clean way to do what I am trying to do as this method is expensive for two reasons:

  1. The column list is very long
  2. I need to do this 1000 time / second
farhawa
  • 10,120
  • 16
  • 49
  • 91
  • 2
    Related thread with a benchmark: http://stackoverflow.com/questions/18453566/python-dictionary-get-list-of-values-for-list-of-keys. – alecxe Apr 27 '16 at 16:02
  • I don't think so, dictionaries are hash tables, so retrieval is O(1) and total complexity is O(n), which is optimal. So you should probably try something completely different – BlackBear Apr 27 '16 at 16:04
  • Nah, as @BlackBear points out, you won't get better than `O(n)`. A little comprehension could be considered cleaner, but won't improve performance. – user2390182 Apr 27 '16 at 16:06
  • I added an additional answer to the "duplicate" – mementum Apr 27 '16 at 16:15

1 Answers1

2

Using a list comprehension is shorter:

myDict = { "age":"value1","size":"value2",'weigth':"value3"}
order_list = ["age","weigth","size"]
result_list = [myDict[x] for x in order_list]

map will do as well:

# Python 3.x (map returns an iterator)
result_list = list(map(myDict.get, order_list))

# Python 2.x (map returns a list)
result_list = map(myDict.get, order_list)
jDo
  • 3,962
  • 1
  • 11
  • 30