I'm trying to create a list with sublists of keys from a dictionary based on elements in another list of sublists (data below).
I have a function attempting to follow this logic:
- See if the element in the sublist matches any exact value in the dictionary
- If it does, append the associated dictionary key to a sublist within a new list
- If not, try to convert the element into an integer and append that to a sublist in the new list
- If that doesn't work, append the whole sublist to an entirely new list
- Return a list with sublists of integers converted from the strings in the original file and a list with sublists that can't be converted
I hope that logic makes sense. Thanks to some comments on a previous version of this question (Replacing elements in a sublist with keys from a dictionary based on matches with dictionary values), I've edited the code and dictionary so the re.search
function now works. Here's the new code below:
import re
def conversion(d, file):
key_list = list(d.keys())
for i in range(0, 21):
for j in file:
for k in j:
good1 = []
good1a = []
good2 = []
good2a = []
bad1 = []
bad2 = []
if k == d[i]:
good1a.append(key_list[i])
good1.append(good1a)
if isinstance(int(k), int):
if int(k) <= 20:
good2a.append(int(k))
good2.append(good2a)
else:
bad1.append(j)
else:
bad2.append(j)
list1 = []
list2 = []
list1.append(good1)
list1.append(good2)
list2.append(bad1)
list2.append(bad2)
return list1, list2
However, this is not outputting what I would expect:
([[], []], [[], []])
This is probably something to do with the placing of my lists or something along those lines but I'm really new to python and I'm not following the logic of where things should go yet.
Any help would be appreciated!
Many thanks,
Carolina
Data:
d = {0: "zero, null",
1: "one, un, eins",
2: "two, deux, zwei",
3: "three, trois, drei",
4: "four, quatre, vier",
5: "five, cinq, funf",
6: "six, sechs",
7: "seven, sept, sieben",
8: "eight, huit, acht",
9: "nine, neuf, neun",
10: "ten, dix, zehn",
11: "eleven, onze, elf",
12: "twelve, douze, zwolf",
13: "thirteen, treize, dreizehn",
14: "fourteen, quatorze, vierzehn",
15: "fifteen, quinze, funfzehn",
16: "sixteen, seize, sechzehn",
17: "seventeen, dix-sept, siebzehn",
18: "eighteen, dix-huit, achtzehn",
19: "nineteen, dix-neuf, neunzehn",
20: "twenty, vingt, zwanzig"}
file = [['16', '10', '8', '3', '7'], ['8', '9', '19', '20', '4'], ['sechs', 'acht', 'sechzehn', 'funf', 'null'], ['1', '30', '2', '5', '7'], ['vierzehn', 'eins', 'zwei', 'neun', 'drei'], ['six', 'neuf', 'seize', 'zero'], ['fourteen', 'eleven', 'forteen', 'eight', 'twenty'], ['douze', 'onze', 'huit', 'quinze', 'sept'], ['18', '9', '9', '22', '4'], ['un', 'trois', 'quatorze', 'dix-huit', 'vingt'], ['five', 'three', 'nineteen', 'twenty', 'zero'], ['einundzwanzig', 'vierzehn', 'eins', 'zwei', 'vier']]