Dynamically defining variables from a dictionary [duplicate] - python

This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 4 years ago.
I am trying to dynamically define variables from a dictionary in python. I need my variables to be strings, they should appear something like this: lightgreen = "#2ecc71". To do this I added HEX_VALUE = "'" + HEX_VALUE + "'" however adding this I encountered an error
> Traceback (most recent call last):
line 22, in <module>
exec("%s=%s" % (COLOUR_NAME, HEX_VALUE))
File "<string>", line 1
darkblue:='#2980b9'
^
SyntaxError: invalid syntax
As seen from above, this adds ':' to the first part of the variable, so my question is: how can I prevent this?
COLOURS = {
"lightgreen":"'#2ecc71'",
"darkgreen":"#27ae60",
"lightblue":"#3498db",
"darkblue:":"#2980b9",
"lightpurple":"#e74c3c",
"darkpurple":"#8e44ad",
"lightred":"#e74c3c",
"darkred":"#c0392b",
"lightorange":"#e67e22",
"darkorange":"#d35400",
"lightyellow":"#f1c40f",
"darkyellow":"#f39c12",
"lightteal": "#1abc9c",
"darkteal": "#16a085",
"lightnavy": "#34495e",
"darknavy": "#2c3e50"
}
for COLOUR_NAME, HEX_VALUE in COLOURS.items():
HEX_VALUE = "'" + HEX_VALUE + "'"
exec("%s=%s" % (COLOUR_NAME, HEX_VALUE))

As some mentioned in the comments, there is no reason to use exec to make python define new variables. The hex values are already strings in the dictionary so you can just access them directly like so:
lightgreen = COLOURS["lightgreen"]
Although I'll not there is no reason to define variables with the same name as the key of the dict since the dict can just always be accessed directly when necessary.

Related

Python list .insert() [duplicate]

This question already has answers here:
Python's insert returning None?
(4 answers)
Closed 5 years ago.
I'm working on a polynomial organizer. I need to insert two items into the list of coefficients and powers, (a zero for the coefficient and the missing power) wherever needed.
print poly
poly=list(poly.split(','))
for i in range(0,13):
if int(poly[i*2+1])!=int(12-i):
poly=poly.insert((i*2+1),str(12-i))
poly=poly.insert((i*2+1),"0")
returns
0,12,0,11,0,10,0,9,0,8,-7,7,1,5,-1,4,1,3,-2,2,5,0
Traceback (most recent call last):
File "python", line 105, in <module>
File "python", line 97, in mypoly
AttributeError: 'NoneType' object has no attribute 'insert'
I'm confused because from what I've read on the insert function, it is made to work on lists, but here it seems not to. Please don't kill this question... I've been trying to figure it out on my own for a while now, and always run into this problem.
So I want it to look like this:
[0,12,0,11,0,10,0,9,0,8,-7,7,0,6,1,5,-1,4,1,3,-2,2,0,1,5,0]
Notice the 0,6 and 0,1.
The method insert of list returns None, since it modifies the list. You have to change poly = poly.insert(...) to just poly.insert(...):
print poly
poly=list(poly.split(','))
for i in range(0, 13):
if int(poly[i*2+1]) != int(12-i):
poly.insert((i*2+1), str(12-i))
poly.insert((i*2+1), "0")

TypeError: locals must be a mapping

In Python 3.4.3 I have this code.
operator = random.choice('-+')
numTheF = random.choice(numsUseF)
numTheS = random.choice(numsUseS)
print ('What is', int(numTheF), operator, int(numTheS))
ansReal = eval(int(numTheF), operator, int(numTheS))
ansUser = input ('?')
if ansUser == ansReal:
score += 1
question += 1
All the variables are properly set up but I can't get the ansReal to output the actual answer.
Here is the error message.
Traceback (most recent call last):
File "C:\Users\Marko\Documents\Programming Princ\Task One.py", line 34, in <module>
ansReal = eval(int(numTheF), operator, int(numTheS))
TypeError: locals must be a mapping
eval() takes three arguments, the latter two of which are optional. The first is the expression (as a string) to evaluate; the latter two, if present, must be mappings that will be used for the global and local namespaces in which to evaluate the expression. See the documentation on eval() for more information.
As Kevin, I do not condone the use of eval(). You're already using int() to parse strings into integers; that's a good start—consider also simply adding or subtracting those integers to get the real answer.

Python enum implementation [duplicate]

This question already has answers here:
How can I represent an 'Enum' in Python?
(43 answers)
Closed 8 years ago.
I have declared the enum as follows in python.I don't know how to use them.When I create an instance of this class it gives error as two arguments are required one given.
class CBarReference(Enum):
ThisBar = 0,
NextBar = 1,
Undefined=2
a=CBarReference()
I know what error is but I don't know what to give as the second argument other than self.
You should never have to create an instance of an enum; they're all accessed directly from the class, and you can just assign them to variables as you like:
a = CBarReference.ThisBar
b = CBarReference.NextBar
c = CBarReference.Undefined
d = CBarReference.ThisBar
assert(a == d)
assert(b != a)
assert(b != c)

Is there a way to append an integer to the end of a variable name in python [duplicate]

This question already has answers here:
How to create an unknown amount of variables in python
(6 answers)
Closed 9 years ago.
after much googling i now ask. Is there a way to append an integer to the end of a variable name. Essentially creating a new variable with each iteration of a for loop. IE:
def parser(lst):
count = 0
for obj in lst:
if isinstance(obj,list):
parser(obj)
else:
for string in obj:
var+count = o
This is what i get when i try to run above code:
SyntaxError: can't assign to operator
You almost certainly want to use a list:
def parser(lst):
vars = []
for obj in data: # did you mean "for obj in lst:"?
if isinstance(obj,list):
parser(obj)
else:
for string in obj:
vars.append(o) # did you mean "vars.append(string)"?
Then, instead of, say, var5, you would use vars[5].
Doorknob of Snow's answer is correct, but for completeness, you can create a new variable using locals()[var + str(count)] = o. But this is a bad idea, so don't.

What Is Subscriptable? [duplicate]

This question already has answers here:
l.append[i], object is not subscriptable? [closed]
(2 answers)
Closed 8 years ago.
exxy = ['mix', 'xyz', 'aardvark', 'xanadu', 'apple']
pleasework = []
ten = []
for s in exxy:
if s[0] == 'x':
pleasework.insert[0, s]
else:
ten.append[s]
pleasework.sort()
ten.sort()
pleasework.append(ten)
print pleasework
I keep getting an error that says that object is not subscriptable.
Traceback (most recent call last):
File "/Users/jerrywalker/Desktop/CompSci/Programming/Programming_Resources/Python/idle.py", line 10, in <module>
ten.append[s]
TypeError: 'builtin_function_or_method' object is not subscriptable
I'm not really sure what this means. I've just started Python yesterday... I'm sure it's something in the code that I'm not doing right, because even when I change the name of my variables around the error is the same.
"Subscriptable" means that you're trying to access an element of the object. In the following:
ten.append[s]
you're trying to access element s of ten.append. Since you want to call it as a function/method instead, you need to use parens:
ten.append(s)
You have defined two lines with the wrong syntax:
It shouldn't be:
pleasework.insert[0, s]
ten.append[s]
But rather:
pleasework.insert(0, s)
ten.append(s)
ten.append(s) is a list method and you cannot try to get a element s of ten.append(s).
Even assuming you were trying to do something like ten[s] it would still return a error because s has to be the index (which is a integer) of the element you want

Categories

Resources