Home > other >  Map elements of a list of lists to a dictionary value
Map elements of a list of lists to a dictionary value

Time:10-07

The problem is pretty straightforward, I have a dictionary in which I have the classes and a number assigned for identification, for example:

{'checkbox': 0,
 'radio': 1,
 'dropdown': 2,
 'listbox': 3,
 'button': 4,
 'link': 5,
 'input': 6,
 'label': 7}

The thing is, the list is composed by other list of different lengths that have these keys values, such as:

[['link',
'dropdown',
'dropdown',
 ['input', 'link'], ['input', 'button', 'link'],
 ['dropdown',
  'button'],...

It is very irregular since it is related to the bounding boxes annotations. So I aimed to use map function and list comprehensions.

# Simply using replace method -> know that, these list of labels is a dataframe column
labels_remapped = df['labels'].replace(Dict)

# Using map(Dictionary, iterable)
labels_remapped = map(Dict, df['labels'])

# Iterating over sublists
labels_remapped = [map(Dict, sublist) for sublist in labels]

However, I didn't succeeded. How can I iterate over this specific list and replace with its corresponding value?

CodePudding user response:

Recursively process deeply into the data:

def deep_map(func, xs):
    if not isinstance(xs, list):
        return func(xs)
    return [deep_map(func, x) for x in xs]

deep_map(lambda x: d[x], xs)

...where d is a dict, and xs is your data.

  • Related