Python incrementally set a variable to equal another variable [duplicate] - python

This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 1 year ago.
I am attempting to set the value of a variable to incrementally equal that of another variable based on the iteration of the loop I am on.
I have the following code:
no_keywords=3
cat_0='Alpha'
cat_1='Bravo'
cat_2='Charlie'
cat_3='Delta'
for _ in range(no_keywords):
keyword1 = exec(f'cat_{_}')
print(keyword1)
However the printed value just returns a NoneType object. I would like the value of Keyword1 to take on the value of the cat_ variable based on the iteration of loop I am on.
Please can somebody help in explaining in what I am doing wrong and help me recitfy?
Thanks,
D

Try this:
no_keywords = 3
cat_0 = 'Alpha'
cat_1 = 'Bravo'
cat_2 = 'Charlie'
cat_3 = 'Delta'
for _ in range(no_keywords):
keyword1 = None
exec(f'keyword1 = cat_{_}')
print(keyword1)
Seems like exec does not return a value, but you can set your variable within the command passed to it.

Related

create python dictionary with same function but different parameters [duplicate]

This question already has an answer here:
Dictionary With Lambda Values Updates All Entries
(1 answer)
Closed 1 year ago.
Hi this puzzeles me for a while now:
I want to add to an existing dictionary a new key with a specific function (myfun) but using different parameters for the same function:
dct = {}
params = {'a':[10,20],'b':[-10,10]}
def myfun(x,y):
return (x+y)
print(myfun(*params['a'])) #desired output for dct['a'](1,1) = 30
print(myfun(*params['b'])) #desired output for dct['b'](1,1) = 0
for key in params.keys():
dct[key]=lambda x,y: myfun(params[key][0]*x,params[key][1]*y)
print(dct['a'](1,1)) # should be 30
print(dct['b'](1,1)) # should be 0
but apparently it keeps only the last key (in this case 'b').
Any ideas?
Thanks #Chris:
use lambda-parameters initialized:
dct[key]=lambda x,y,xx=params[key][0],yy=params[key][1]: myfun(xx*x,yy*y)
this resolved my question!

How to get the value from JSON key and update it accordingly? [duplicate]

This question already has answers here:
Edit the values in a list of dictionaries?
(4 answers)
Closed 1 year ago.
I have the following JSON, I want to be able to get the value for a certain key and update it accordingly.
So for example take a look at the key 'a' in the first JSON object, I want to be able to get its value '2' and then update the value for 'a' to whatever I want. It is important I can work with the value, incase I want to reformat date/time for example and update the key.
All help appreciated
x = "test" : [{
"a":"2",
"b":"12",
"c":"24",
"d":"223",
"e":"23",
},
{"a":"22",
"x":"24",
"c":"25",
"d":"21",
"e":"25",
},
{"a":"12",
"y":"23",
"c":"25",
"d":"23",
"e":"21",
}],
You could do this.
keyFor = 'a'
#get value
aVal = x['test'][0][keyFor]
#change value
aVal = int(aVal) + 2
#substitute in x
x['test'][0][keyFor] = aVal
print(x)

Create Variable Name When Defining A Function [duplicate]

This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 1 year ago.
I am working in Python trying to write a function using a list of variables.
Here is the data I am working with:
material_list=['leather', 'canvas', 'nylon']
def materialz(MAT):
MAT=support.loc[(material==MAT)].sum()
for i in enumerate(material_list):
materialz(i)
What I am looking for is to pass in each of the items in the list to the function to produce global variables.
leather=
canvas=
nylon=
Any help would be appreciated!
You could create a dictionary and dynamically assign the key-value pairs there. Such as:
material_list=['leather', 'canvas', 'nylon']
material_dict={}
for i in enumerate(material_list):
material_dict[i]=value #Where i would be the key and value the value in the key-value pair
you can use exec
var = 'hello'
output = hello
exec('var = "world"')
print(var)
output = world

How to make string f-string after variable initiazation? [duplicate]

This question already has answers here:
How to postpone/defer the evaluation of f-strings?
(14 answers)
Closed 3 years ago.
Let's suppose I get some string and set it to variable - it can't be created as f-string:
str1 = 'date time for {val1} and {val2}'
Then variables inside the string initialized:
val1 = 1
val2 = 77
Calling print(str1) will return 'date time for {val1} and {val2}'. But I would like to get
'date time for 1 and 77'
Is there any function to make a string as a F string? So I want to call something make_F(str1) and get f-string
PS I cant use dict {'val1':1, 'val2':77} with .format because don't know which variables will be needed in the string. I just want magic happen with F-string.
You need:
str1 = 'date time for {val1} and {val2}'
val1 = 1
val2 = 77
print(eval(f"f'{str1}'"))
You first need to describe variables as e.g
var1 = None
var2 = None
Then you can use it with f-string like this:
x = f'print {var1} and {var2}'
print(x)
And thats it, you will get the result.

How can I dynamically create a name of a variable in Python? [duplicate]

This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 5 years ago.
I am having a function in python
def func(dataFrame,country,sex):
varible_name=dataFrame[(dataFrame['land']==country) & (dataFrame['sex']==sex)]
Now, for example, I call this function
func(dataFrame,'England','M')
I want that variable name be England_M instead of variable_name.
You can't do that in Python.
What you can do instead is store the results under a dictionary with key = England_M for instance.
In your case, you could do the following :
def func(dataFrame,country,sex):
tmp = dataFrame[(dataFrame['land']==country) & (dataFrame['sex']==sex)]
variable_name = "{c}_{s}".format(c=country, s=sex)
return dict(variable_name=tmp)
Now using it :
results = func(dataFrame, "England", "M")
print(results['England_M'])

Categories