I want my for loop to change the variable if there is a KeyError
,
numlist1 = {"one": 1}
numlist2 = {"two": 3}
numlist3 = {"three": 3}
userinputfix = ["two", "five"]
newlist = []
for x in userinputfix:
newlist.append(numlist1[x])
So if there is no "two" in numlist1, it should repeat the loop replacing numlist1 with numlist2, numlist3,...
I tried to use handling exceptions method:
numlist1 = {"one": 1}
numlist2 = {"two": 3}
numlist3 = {"three": 3}
userinputfix = ["two", "five"]
y = 1
newlist = []
for x in userinputfix:
try:
newlist.append(numlist{y}[x])
except KeyError:
y = 1
Something like the above but my code is not correct.
CodePudding user response:
So, I 'think' you want to produce an output of [2] for the above? I.e. taking a list of matching values from each of the lists ignoring those that don't have a matching key?
You can't access 'numlist2' by using 'numlist{2}' as you're attempting there. If there is a short, fixed number of lists, you need to iterate them specifically:
newlist = []
for x in userinputfix:
for d in (numlist1, numlist2, numlist3):
try:
newlist.append(d[x])
except KeyError:
pass
If you want to use any dictionary that starts "numbest", then it'll be something horrible like...
dicts = [globals()[x] for x in globals() if x.startswith("numlist") and type(globals()[x]) == dict]
newlist = []
for x in userinputfix:
for d in dicts:
try:
newlist.append(d[x])
except KeyError:
pass
This makes a list of all global variables that start 'newlist' and are dictionaries, then those are iterated.
CodePudding user response:
Here is using dict.get
and while
loop with try except
and eval
numlist1 = {"one": 1}
numlist2 = {"two": 3}
numlist3 = {"three": 3}
numlist4 = {"four": 4}
userinputfix = ["four", "two", "five", "one"]
newlist = []
i = 1
for x in userinputfix:
while True:
try:
val = eval(f'numlist{i}').get(x)
if val != None:
newlist.append(val)
i = 1
except NameError:
break
i = 1
print(newlist)
# [4, 3, 1]
For each x
in userinputfix
, it will try to find x
in every dictionaries variable by increasing i
by 1 until it found NameError
and resetting i
back to 1 to continue to the next x
. If the value is None
or x
not found, it'll not get appended to newlist
.