Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method for mapping dictionary values in complex list

Inputs

I have a very complicated list of list.

total_aug_rule_path_list = 
[[[[['#1_0_0', '#2_0_0', '#3_0_0'], ['#1_0_1', '#2_0_1', '#3_0_1']],
   [['#1_0_0', '#2_0_0', '#3_0_0'], ['#1_0_1', '#2_0_1', '#3_0_1']]],
  [[['#1_1_0', '#2_1_0', '#3_1_0', '#4_1_0'],
    ['#1_1_1', '#2_1_1', '#3_1_1', '#4_1_1']]]]]

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

sym2id_dict = {
 '#1_0_0': 1,
 '#1_0_1': 2,
 '#1_1_0': 3,
 '#1_1_1': 4,
 '#2_0_0': 5,
 '#2_0_1': 6,
 '#2_1_0': 7,
 '#2_1_1': 8,
 '#3_0_0': 9,
 '#3_0_1': 10,
 '#3_1_0': 11,
 '#3_1_1': 12,
 '#4_1_0': 13,
 '#4_1_1': 14,}

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

output

[[[[[1, 5, 9], [2, 6, 10]], [[1, 5, 9], [2, 6, 10]]],
  [[[3, 7, 11, 13], [4, 8, 12, 14]]]]]

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

list(map(lambda proofpaths_to_goal : 
list(map(lambda proofpaths_to_template :
list(map(lambda proofpath :
list(map(lambda single_augment : list(map(lambda x : sym2id_dict[x], single_augment)),  
     proofpath)), proofpaths_to_template)), proofpaths_to_goal)),total_aug_rule_path_list))

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

like image 982
Won chul Shin Avatar asked Sep 02 '26 20:09

Won chul Shin


1 Answers

You could convert the list to a string literal, and replace the respective string from the dictionary using regular expression, then convert the string literal back to a list.

import re
import ast

s = str(total_aug_rule_path_list)   #converts to string literal
for element in re.findall(r'#\d_\d_\d', s):
    s = s.replace(element, str(sym2id_dict[element]))
s = s.replace("'", "")   #because each integer is a string
s = ast.literal_eval(s)   #converts string literal back to list, do NOT use eval(s)
print(s)

Edit: Please note it is dangerous to use eval() in any language (python, perl, js, etc) because it makes code injection bugs possible. Instead to be safe, use ast.literal_eval().

Output

[[[[[1, 5, 9], [2, 6, 10]], [[1, 5, 9], [2, 6, 10]]],
  [[[3, 7, 11, 13], [4, 8, 12, 14]]]]]
like image 82
Black Raven Avatar answered Sep 04 '26 09:09

Black Raven



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!