Skip to content
Advertisement

Method for mapping dictionary values in complex list

Inputs

I have a very complicated list of list.

JavaScript

And i have a dictionary that has each element of the list as a key.

JavaScript

I’m going to map each element of the list to the value of the dictionary.

output

JavaScript

I tried the following to use the for loop as little as possible.

JavaScript

I would appreciate it if you could let me know if there is a way that is easier or more readable than this method.

Advertisement

Answer

Here are a few alternatives:

Nested list comprehension

JavaScript

Though this is arguably no easier to read.

Using Numpy

This method does not work for your example list because numpy arrays must not be ragged arrays (i.e. all lists that are equally nested must have the same length). However, when you are not using ragged arrays, you can do:

JavaScript

This applies the sym2id_dict.get function to every string in the array. You can change this to sym2id_dict._getitem__ if you want it to throw an error when the key is not in the dictionary.

Write your own recursive function

Recurse and iterate through lists

This function recurses until the input isn’t a list. This will work on lists like [1, [2, 3]]. If you want it to work on things other than lists, see here.

JavaScript

Fixed recursion depth

This variation recurses to a fixed depth, so no isinstance checking is needed:

JavaScript

If you really want, you could use a trick with itertools.accumulate to make this fixed recursion depth function into a single expression, but it’s pretty unpythonic and hard to understand.

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement