This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 2 years ago.
How to assign variable names programmatically in python?
I have a lot of objects and their names are not predefined. Currently I am reading in from a file which has names in it and I’m reading in them into a list. But from this list how do I assign the names to the variables so that variables are easy to remember and work with. I cannot hard code because :
a. I don’t want them to be fixed
b. I have a lot of names so it is not feasible to type in. (Even copy paste every name)
Use dictionaries. (And assign its keys programmatically!)
You can assign the variables names which you’ve already read into the list and then have their values read. I’m still not clear about how you want your values but assuming you have them in a list too as you have your variable names, then just zip both lists as dict:
data = dict(zip(names, values))
Now you can access each variable by its name as follows:
data['name']
Related
This question already has answers here:
using locals() inside dictionary comprehension
(2 answers)
Closed last year.
Inside a script I have conditions to created variables with names of files. At the end of the script I want to know which variables were created. I use in locals() function to check it. If I do if with a simple list building it works fine, but with list comprehension I don't get the results. Why?
To be clear, I don't need suggestions to bypass the problem (I can just use the simple list building), just an explanation to the behaviour.
In my example file_08 and file_14 variables were created, but file_15 wasn't.
all_files = []
for file in ['file_08', 'file_14', 'file_15']:
if file in locals():
all_files.append(file)
print(all_files)
['file_08', 'file_14']
Works, but:
print([file for file in ['file_08', 'file_14', 'file_15'] if file in locals()])
[]
Doesn't work
The locals() function returns a dictionary containing the variables defined in the local namespace. Unless you have defined variables with the names 'file_88', 'file_14', and 'file_15' within the executable name space, you will get an empty list. You can verify this by printing the contents of locals() and see what you get back.
This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 2 years ago.
I've seen this question a few times before, and invariably I see that people always respond by saying that this is a bad idea. What is a good way to approach this issue?
I have a code that reads in data from several csv files in a for loop, i.e for each loop iteration a different csv is read. At the end of my for loop, I make a dictionary with some data in it. All I would like to do is name this dictionary after the original csv file's name.
At the moment I have:
sessionname=str(inputList).replace(".csv",'').replace("'",'').replace("[",'').replace("]",'')
session_dict={}
What I would like is for session_dict to be named using the string in sessionname.
Therefore at the end of my for loop, I would have a number of dictionaries each with the name of its orginal csv file.
Thank you!
You can't create a variable named after a filepath, because of the slashes and the spaces, etc.
One thing you can do is to name each of your dictionaries with a number (or a unique code), and in run-time create a reference dictionary like:
ref_dict = {r'csv_file_0_path' :0, r'csv_file_1_path': 1, r'csv_file_2_path': 2}
and so on.
This question already has answers here:
How do I create variable variables?
(17 answers)
How can I create multiple variables from a list of strings? [duplicate]
(2 answers)
generating variable names on fly in python [duplicate]
(6 answers)
Closed 3 years ago.
I have a ticker and I want to check a specific list of tickers to see if the ticker is found. If it is found, it will replace it.
The new tickers come from another data source and therefore do not know which specific list of tickers to check. In order to find that list, I can pass the lists name as a string but upon iterating the code (naturally) recognizes this as string as opposed to a list to iterate.
Is there a way to have the code/function recognize that the string is actually a specific list to be checked? In reading other questions, I know this may not be possible...in that case what is an alternative?
list_1=['A','B']
list_2=['C','D']
old_ticker='A'
new_ticker='E'
assigned_list='list_1'
def replace_ticker(old_ticker,new_ticker,list):
for ticker in list:
if new_ticker in list:
return
else:
list.append(new_ticker)
list.remove(old_ticker)
replace_ticker(old_ticker,new_ticker,assigned_list)
You key the needed lists by name in a dictionary:
ticker_directory = {
"list_1": list_1,
"list_2": list_2
}
Now you can accept the name and get the desired list as ticker_directory[assigned_list].
list_1=['A','B']
list_2=['C','D']
lists = {
'list_1':list_1,
'list_2':list_2
}
old_ticker='A'
new_ticker='E'
assigned_list='list_1'
def replace_ticker(old_ticker,new_ticker,list_name):
if old_ticker not in lists[list_name]:
return
else:
lists[list_name].append(new_ticker)
lists[list_name].remove(old_ticker)
replace_ticker(old_ticker,new_ticker,assigned_list)
print(lists[assigned_list])
This is the complete program from what i perceived.
#prune already answered this, I have just given the whole solution
There are at least two possibilities:
1 As noted in comments kind of overkill but possible:
Use eval() to evaluate string as python expressions more in the link:
https://thepythonguru.com/python-builtin-functions/eval/
For example:
list_name = 'list_1'
eval('{}.append(new_ticker)'.format(list_name))
2 Second
Using locals() a dictionary of locally scoped variables similiar to the other answers but without the need of creating the dict by hand which also requires the knowledge of all variables names.
list_name = 'list_1'
locals()[list_name].append(new_ticker)
This question already has answers here:
Why doesn't assigning to the loop variable modify the original list? How can I assign back to the list in a loop? [duplicate]
(4 answers)
Closed 5 months ago.
I have a list and want to change its elements
list = ['apple','potato']
Now, while this works
for i in range(list):
list[i] = list[i].capitalize()
this one doesn't and I just don't get why
for i in list:
i = i.capitalize()
I'm new to Python, my only background is C++ so I'm still trying to adapt to Python's style. If this kind of question had already been asked, please, feel free to redirect me and close this topic. Thank you!
Assigning in the loop will create a new name i inside the for that loses its value after each iteration.
That isn't really the point here though. You can have the effect get noticed if you were dealing with mutable substructures that can be altered in-place, i.e:
l = [[1], [2]]
for i in l:
i.append(2)
changes will get reflected accordingly (sub-list will be get 2 appended to them).
in your case, though, you have strs which are immutable objects. i.capitalize(), acting on a str instance will create a new copy of the value which is assigned and then lost. It will not affect the objects inside the list.
The value i in for i in container: does refer to the objects contained in the sequence. When you assign i to the result of i.capitalize(), the name i will now refer to the new capitalized instance returned.
Don't try and draw parallels between C++ and Python, I know it sometimes makes learning easier but, other times, in can confuse the hell out of you.
Mandatory note: don't use list as a name, it masks the built-in name list.
This question already has answers here:
Dictionary use instead of dynamic variable names in Python
(3 answers)
Closed 7 years ago.
From a shapefile I create a number of csv files but I don't know how many of them will be created each time. The csv files are named road_1, road_2 etc.
In these files, I have coordinates. I would like to put the coordinates of every csv files in lists.
So for road_1 I would like 3 lists:
x_1, y_1, z_1
For road_2:
x_2, y_2, z_2 etc.
I tried to name the lists in the loop where I get the coordinates with this : list+'_'+i where i is iterating through the number of files created, but i cannot concatenate a list and a string.
**
EDIT
**
Ok, some marked this topic as duplicated, fair enough. But just saying that I have to use a dictionnary doesn't answer all of my question. I had thought of using a dictionnary but my main issue is creating the name (either the name of the list, either the key of a dictionnary). I have to create this in a loop, not knowing how many I have to create. Thus, the name of the list (or key) should have a variable which must be the number of the road. And it's here that I have a problem.
As I said before, in my loop i tried to use a variable from the iteration loop to name my list but this didn't work, since it's not possible to concanate list with string. I could create an empty dictionnary with many empty key:value pairs, but I would still have to go through the keys name in the loop to add the values from the csv file in the dict.
Since it has been asked many times I wont write the code but only point you in the right direction (and maybe a different approach).
Use the glob module which will return the file names. Something like:
import glob
for csvFileNames in glob.glob("dir/*.csv"):
will return you each filename into the variable csvFileNames.
Then you simply open you csv Files with something like:
with open(csvFileNames, "r") as filesToRead:
for row in filestoRead:
#the structure of you csv File is unknown so cannot say anything here
Then its simple. Find you columns your interested in and create a dicts with the variables you need as keys. Use a counter to increment. All the information is there!