I am trying to create an array of hash in python but it is not working
data = ["long","short","fanouts"]
app = []
for da in data:
app.append(app[name] = da)
output
File "test.py", line 5
app.append(app[name] = da)
SyntaxError: keyword can't be an expression
Please could anyone help me with correct code i am new to python
When you write
abc(x=y)
the interpreter reads that as trying to call a function with a keyword argument. So reading your line
app.append(app[name] = da)
it thinks you have a keyword argument app[name], which does not make sense as a keyword argument.
If you want to append a dict to your list, you could do it like this:
app.append({name:da})
as long as name and da are existing variables.
Try this:
data = ["long","short","fanouts"]
app = []
for da in data:
app.append({name: da})
Depends on what you want app[name] to be (assuming app is a dict). Either
app[name].append(da)
or
app.update(name=da)
Related
I currently have the following file load.py which contains:
readText1 = "test1"
name1 = "test1"
readText1 = "test2"
name1 = "test2"
Please note that the number will change frequently. Sometimes there might be 2, sometimes 20 etc.
I need to do something with this data and then save it individually.
In my file I import load like so:
from do.load import *
#where do is a directory
I then create a variable to know how many items are in the file (which I know)
values = range(2)
I then attempt to loop and use each "variable by name" like so:
for x in values:
x = x + 1
textData = readText + x
nameSave = name + x
Notice I try to create a textData variable with the readText but this won't work since readText isn't actually a variable. It errors. This was my attempt but it's obviously not going to work. What I need to do is loop over each item in that file and then use it's individual variable data. How can I accomplish that?
This is a common anti-pattern that you are stepping into. Every time you think "I'll dynamically reference a variable to solve this problem" or "Variable number of variables!" think instead "Dictionary".
load.py can instead contain a dictionary:
load_dict = {'readText1':'test1','name1':'test1','readText2':'test2','name2':'test2'}
You can make that as big or small as you want.
Then in your other script
from do.load import *
#print out everything in the dictionary
for k,v in load_dict.items():
print(k,v)
#create a variable and assign a value from the dictionary, dynamically even
for x in range(2):
text_data = load_dict['readText' + x]
print(text_data)
x+=1
This should allow you to solve whatever you are trying to solve and won't cause you the pain you will find if you continue down your current path.
If you are trying to access the variables in the module you've imported, you can use dir.
loader.py
import load
values = dir(load) # All the values in load.py
# to get how many they are
num_vars = len([var for var in module_vars if not var.startswith("__")])
print(num_vars)
# to get their names
var_names = [var for var in module_vars if not var.startswith("__")]
print(var_names)
# to get their values
var_values = [globals()[f"module.{var}"] for var in var_names]
print(var_values)
However, it is unsafe as it may introduce security vulnerabilities to your code. It is also slower. You can use data structures as JNevil has said here, here
The file load.py will load only the last variable "readText1" and "name1".
To do what you are asking for, you have to open load.py file as a text file and then iterate over each line to get 2 variables ("readText1" and "name1") for each iteration.
I am trying to create a program that modify different dbf file but since each file have different field name, I am unsure if the python dbf library have the option to specify the field with string.
To modify the data without variable
dbf.write(record, CUSTOM2="Hello")
But when I tried this, it gives an error
dbf.write(record, {'CUSTOM2': "Hello"})
TypeError: write() takes 1 positional argument but 2 were given
There are a couple ways to update records in dbf files:
use the record as a context manager:
target_field = 'custom2'
with record:
record[target_field] = "Hello"
or use the write function with keywords:
target_field = 'custom2'
update = {target_field: "Hello"}
dbf.write(record, **update)
My code uses pandas to extract information from an excel sheet. I created a function to read and extract what I need and then I set it as two variables so I can work the data.
But the start of my code seems a bit messy. Is there a way to rewrite it?
file_locations = 'C:/Users/sheet.xlsx'
def process_file(file_locations):
file_location = file_locations
df = pd.read_excel(fr'{file_location}')
wagon_list = df['Wagon'].tolist()
weight_list = df['Weight'].tolist()
It seems stupid to have a variable with the file destination and then set the file_location for pandas inside my function as the variable.
I'm not sure if I could use file_location as the variable outside and inside the function I would call file_location = file_location.
Thanks for any input!
You can simply remove the setting of the file location inside the function.
file_location = 'C:/Users/sheet.xlsx'
def process_file():
df = pd.read_excel(fr'{file_location})
wagon_list = df['Wagon'].tolist()
weight_list = df['Weight'].tolist()
But it depends on what you are trying to do with the function as well. Are you using the same function with multiple files in different locations? or is it the same file over and over again.
If it's the later then this seems fine.
You could instead do something like this and feed the location string directly into the function. This is more of a "proper" way to do things.
def process_file(file_location):
df = pd.read_excel(file_location)
wagon_list = df['Wagon'].tolist()
weight_list = df['Weight'].tolist()
process_file('C:/Users/sheet.xlsx')
I have recently started writing small Python program blocks in SPSS.
In my current dataset I coalesce two variables like this:
BEGIN PROGRAM PYTHON3.
import spss, spssdata
data = spssdata.Spssdata(indexes = ('var1', 'var2'), accessType = 'w')
data.append(spssdata.vdef("newvar"))
data.commitdict()
for row in data:
if row.var1== None:
data.setvalue("newvar", row.var2)
else:
data.setvalue("newvar", row.var1)
data.CClose()
END PROGRAM.
The above program works perfectly well and now I would like to create a function as I need to coalesce many more variables.
The best solution I came up with so far is this one:
BEGIN PROGRAM PYTHON3.
import spss, spssdata
def coalesce(var1, var2, newvar):
data = spssdata.Spssdata(indexes = (var1, var2), accessType = 'w')
data.append(spssdata.vdef(newvar))
data.commitdict()
for row in data:
if row.var1 == None:
data.setvalue("newvar", row.var1)
else:
data.setvalue("newvar", row.var2)
data.CClose()
END PROGRAM.
However, I get the following error message when trying to run it on my variables:
BEGIN PROGRAM PYTHON3.
coalesce('Statements1', 'Statements2', 'Statements12')
END PROGRAM.
Warning: An open Cursor was detected while exiting a program block. The Cursor has been closed.
Traceback (most recent call last):
File "<string>", line 2, in <module>
File "<string>", line 8, in coalesce
AttributeError: 'namedTuple' object has no attribute 'var1'
I suppose that the problem is that I am passing the tuple name rather than the tuple in line 8 but I don't know how to fix that. Already tried different solutions, e.g., tried to pass the variable without quotes in the function but this did not work either. Also, tried to do something like row[var1] in line 8 but it seems that spssdata is not able to work with that.
Anyone who can help me with this problem? Thank you!
In the meantime I came up with a solution myself.
Maybe not the most elegant one but it works fine.
In the "set.value" part in which the error ocurred I am now taking advantage of the fact that the variable row is a tuple, which can also be accessed by index. So, row[0] refers to the values of var1 and row[1] the values of var2.
Furthermore, I am using SPSS to rename the new variable after creating it.
BEGIN PROGRAM PYTHON3.
import spss, spssdata, spssaux
def coalesce(var1, var2, nameAggregate):
#get Variable dictionary info in order to get variable label
sDict = spssaux.VariableDict(caseless = True)
var1Label = sDict[var1].VariableLabel
#create data cursor
data = spssdata.Spssdata(indexes = (var1, var2), accessType = 'w')
data.append(spssdata.vdef("newvar"))
data.commitdict()
for row in data:
if row[0] == None:
data.setvalue("newvar", row[1])
else:
data.setvalue("newvar", row[0])
data.CClose()
#copy label and add "COALESCED" as a prefix
spss.Submit(r"""
APPLY DICTIONARY FROM *
/source variables = %(var1)s
/target variables = newvar
/VARINFO MISSING VALLABELS=REPLACE.
VARIABLE LABELS newvar "COALESCED: %(var1)s & %(var2)s %(var1Label)s".
RENAME VARIABLES (newvar = %(nameAggregate)s).
"""%locals())
END PROGRAM.
Example use:
BEGIN PROGRAM PYTHON3.
coalesce('Statement1', 'StatementsNot1', 'AggregateStatement1')
END PROGRAM.
I further recommend this resource for python programming inside SPSS https://www.spsstools.net/en/documents/76/SPSS-Programming-and-Data-Management-3rd-Edition.pdf
Hello whoever is reading this.
I am having trouble taking a python function from an excel spreadsheet and then running it in python.
I'd like to stress on the fact that I actually defined my function in python, and it's not an excel function.
Please note that this is my second time questioning and have only ever done coding as a hobby.
Here is an example of what I want to take:
heal(2,c)
I am using xlrd to analyze data on the spreadsheet.
Here is a chunk from my code.
e = worksheet.cell(rowidx,colidx+1)
f = str(e).replace("'","")
g = f.replace("text:","")
This chunk focuses on converting the 'cell object' to a 'string' and making it look like the function required.
The end result is this:
g = heal(2,c)
My problem is that I cannot seem to activate this function.
I have also tried doing "g()" but it came up with the error message:
File "C:\Users\Alexander\Dropbox\Documents\Python\Hearthstone\Hearthstone.py", line 18, in play
g()
TypeError: 'str' object is not callable
I do not mind if you tell me a way to activate "g" or just directly run it from the spreadsheet.
Please let me know if you need any more information.
Thank you for you time.
You can use eval for same. Here, I am considering that funciton is defined in current file only.
Example:
eval('heal(2,c)')
If function is defined in other file i.e. "file",import it and call using:
Example:
import file
eval('file.heal(2,c)')