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)
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']
This question already has answers here:
Why does foo.append(bar) affect all elements in a list of lists?
(3 answers)
How do I clone a list so that it doesn't change unexpectedly after assignment?
(24 answers)
Closed 4 years ago.
I am looking to randomly generate a list and change one element in the list to create a new list. Whilst keeping track of all the generated lists.
For example:
values_possible = [0,0.5,1]
combinations = []
combinations.append([random.choice(values_possible) for i in range(8)])
lets say this generates
[0,0.5,0.5,0,0.5,0.5,1.0,1.0]
then if I copy this list and change one element, say combinations[1][1]
# set a new list to equal the first and then change one element
combinations.append(combinations[0])
combinations[1][1] = 0.33
print(combinations[0])
print(combinations[1])
this returns
[0,0.33,0.5,0,0.5,0.5,1.0,1.0]
[0,0.33,0.5,0,0.5,0.5,1.0,1.0]
it seems both combinations[0][1] and combinations[1][1] have changed to 0.33. Is there a way to solve this? May I ask why this happens and what I am misunderstanding about lists? I had expected the following output:
[0,0.5,0.5,0,0.5,0.5,1.0,1.0]
[0,0.33,0.5,0,0.5,0.5,1.0,1.0]
The short answer to your question is using colon:
combinations.append(combinations[0][:])
Why? The reason is that in python when you append a variable into your list, the variable is appended by its reference. In your example, it means that the two elements in the list are the same. They are pointing to the same address in the memory and if you modify either of them, both value will change as they are one and using the same chunk of memory.
If you want to copy the values of a variable, in your case, combinations[0], you need to use colons to make a copy of values and put them in another part of memory (it will occupy another chunk of memory with different address) In this case, you can modify them separately.
You can also take a look at this question and answer: python list by value not by reference
I hope this helps.
use
combinations.append(list(combinations[0]))
to append a copy of the first element.
This question already has answers here:
How to remove an element from a list by index
(18 answers)
Closed 8 years ago.
I'm writing a statistics program which will maintain a list of float values. The program will implement the following menu:
Add value to list
Delete value from list (by value)
Delete value from list (by location in list)
Display list
Exit
I've written everything except the third option. I can't figure out how to get it done. How would one do that?
In Python you can delete an item from a list by referencing it. Like this:
del list[location]
This question already has answers here:
Python Dictionary DataStructure which method d[] or d.get()?
(5 answers)
Closed 8 years ago.
I have written a bit of code using
setting value
dic["key"] = "someval"
and fetching it the same way
print dic["key"]
then I discovered that an alternative way to fetch a dictionary value is to use
print dic.get("key")
I want all my code to use the same method, so should I rewrite all using dic.get("key") ?
If you have a flat dictionary and you want to add or modify a key/value pair, than the best way is to use a simple assignment:
h[key] = value
The get method is useful when you want to get a value from a dictionary for existing keys or use a default value for non-existing keys:
print h.get(key, "Does not exist!")