1

If I have a dictionary whose values are lists, how can slice that list based on indexes? For example:

a = {"x": [1,2,3,4], "y": [10,20,30,40]}

I have the list of indexes, called indexes = [0,2]. I want to get a = {"x": [1,3], "y": [10,30]}. How can I do it without rebuilding the dictionary? I know I can do it something like

{key: dict_name[key][indexes] for key in dict_name}

but I guess it might be inefficient because it re-builds the dictionary?

Thanks!

eng2019
  • 953
  • 10
  • 26
  • These are two problems: (1) how to get a list of values from a list given a list of indexes; (2) how to do the same for multiple lists inside a dictionary; presumably your actual question focuses on (1), since you have shown a correct solution for (2)? – mkrieger1 Jul 02 '21 at 16:58
  • 1
    It doesn't rebuild the dictionary, it builds *another* dictionary. If you want a dictionary as result, this is what you have to do. – mkrieger1 Jul 02 '21 at 16:59
  • Does this answer your question? [In Python, how do I index a list with another list?](https://stackoverflow.com/questions/1012185/in-python-how-do-i-index-a-list-with-another-list) – mkrieger1 Jul 02 '21 at 17:01
  • 1
    You can do it in-place but creating a new dictionary is fine, are you actually worried about memory consumption? – juanpa.arrivillaga Jul 02 '21 at 17:12

2 Answers2

2

You can use a dict comprehension to loop over the original list items, then for each sublist in values use a list comprehension to index out from your indexes

>>> {k: [v[i] for i in indexes] for k,v in a.items()}
{'x': [1, 3], 'y': [10, 30]}
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
1

You can modify the existing dictionary by using slice assignment to change the list contents:

for lst in a.values():
    lst[:] = [lst[i] for i in indices]
kaya3
  • 47,440
  • 4
  • 68
  • 97