I have a list of names I would like to pass to some variables, however the variables have each a unique name. I'm iterating through because in this example the variables seem few but in my real scenario the would be to much to write out and assign a list value.
names = ["apple", 1, 50, "boat", 5, 90, "tree", 4, 96]
n1=q1=t1=""
n2=q2=t2=""
n3=q3=t3=""
name = 0
quantity = 1
total = 2
value = len(names)
value = (value // 3) 1
for i in range(1, value):
tempN = "n" str(i)
tempQ = "q" str(i)
tempT = "t" str(i)
# using locals(), when i print the variables, n1, q1, t1...they all end up empty .
# using exec() I get this error, all the examples to solve this error wasn't very helpful
# since most of them had to do with input from the user.
# File "<string>", line 1, in <module>
# NameError: name 'apple' is not defined
locals()[tempN] = names[name]
locals()[tempQ] = names[quantity]
locals()[tempT] = names[total]
exec("%s = %s" % (tempN, names[name]))
exec("%s = %s" % (tempQ, names[quantity]))
exec("%s = %s" % (tempT, names[total]))
name = 3
quantity = 3
total = 3
This is somewhat a very big oversimplification but the idea remains the same, I have many variables that need to get a value from the list. everything can be changed but the lists format, or the fact that it is a list.
Does anyone know a better way to do this or have a solution to my problem?
CodePudding user response:
You should make use of Python's data structures, especially dictionaries, which will usually result in less code written and makes your code more readable than using eval function.
from collections import defaultdict
result = defaultdict(dict)
keys = ['name', 'quantity', 'total']
names = ["apple", 1, 50, "boat", 5, 90, "tree", 4, 96]
for i, values in enumerate(
[names[x:x len(keys)] for x in range(0, len(names), len(keys))]
):
result[i] = dict(zip(keys, values))
print(result)
Out:
defaultdict(<class 'dict'>,
{0: {'name': 'apple', 'quantity': 1, 'total': 50},
1: {'name': 'boat', 'quantity': 5, 'total': 90},
2: {'name': 'tree', 'quantity': 4, 'total': 96}})
CodePudding user response:
I think just splitting the list into sublists could help you
list = ["apple", 1, 50, "boat", 5, 90, "tree", 4, 96]
sublists = [list[x:x 3] for x in range(0,len(list),3)]
for element in sublists:
print(element)
OUTPUT
['apple', 1, 50]
['boat', 5, 90]
['tree', 4, 96]
