I would like to make a dictionary to compare two values and see if they are equal or not. How would you do this (see value of compareDict -third element of list) since I get a syntax error.
Is there a more elegant way to do this?
def script_sanityCheck(shotDict):
#retrieve data from current script
script_frange = (nuke.root()['first_frame'].value(), nuke.root()['last_frame'].value())
script_fps = nuke.root()['fps'].value()
script_projectname = nuke.root()['project'].value()
script_code = nuke.root()['shotcode'].value()
script_neutralgrade = nuke.root()['neutralgrade_cdl'].value()
#extract data from dictionary
sg_frange = (shotDict['sg_cut_in'], shotDict['sg_cut_out'])
sg_fps = shotDict['sg_fps']
sg_projectname = shotDict['project.Project.name']
sg_code = shotDict['code']
sg_neutralgrade = shotDict['sg_neutralgrade_cdl']
#compare both
compareDict = {
'frange' : [script_frange, sg_frange, True if script_frange == sg_frange else False]
'fps' : [script_fps, sg_fps, True if script_fps == sg_fps else False]
'projectname' : [script_projectname, sg_projectname, True if script_projectname == sg_projectname else False ]
'code' : [script_code, sg_code, True if script_code == sg_code else False]
'neutralgrade' : [script_neutralgrade, sg_neutralgrade, True if script_neutralgrade == sg_neutralgrade else False]
}
pprint(script_sanityCheck(shotDict))
Use dicts from the start to organize your data. That will allow you to build your comparison with a dict comprehension:
def script_sanityCheck(shotDict):
#retrieve data from current script
script = {'frange': (nuke.root()['first_frame'].value(), nuke.root()['last_frame'].value()),
'fps': nuke.root()['fps'].value(),
'projectname': = nuke.root()['project'].value(),
'code': nuke.root()['shotcode'].value(),
'neutralgrade': nuke.root()['neutralgrade_cdl'].value()}
#extract data from dictionary
sg = {'frange': (shotDict['sg_cut_in'], shotDict['sg_cut_out']),
'fps': shotDict['sg_fps'],
'projectname': shotDict['project.Project.name'],
'code': shotDict['code'],
'neutralgrade': shotDict['sg_neutralgrade_cdl']}
#compare both
compareDict = {key: [script[key], sg[key], script[key] == sg[key]] for key in sg}
return compareDict
pprint(script_sanityCheck(shotDict))
Note also that True if a == b else False is simply a == b.
Related
I am trying to update the dictionary "menu" values by getting a value from an appropriate dictionary. I try the following code and get the desired result. But I expect some other alternate ways and a more generic solution in a pythonic way.
Code
language = {"english" : {"lbl01":"File" ,"lbl02":"Accounts"},
"tamil" : {"lbl01":"கோப்பு" ,"lbl02":"கணக்கியல்"},
"hindi" : {"lbl01":"Hindi_File","lbl02":"Hindi_accounts"}}
scut = {"user1": {"lbl01":"Alt+F","lbl02":"F5"},
"user2": {"lbl01":"Ctrl+F","lbl02":"Shift+F5"}}
menu = {"lbl01" :{"id":"file" ,"lan1":"","lan2":"","scut":""},
"lbl02" :{"id":"accounts","lan1":"","lan2":"","scut":""}}
user = ["user2"]
selected_lan = ["tamil","hindi"]
menukey_lst,submenukey_lst =[],[]
for menukey,menuvalue in menu.items():
if menukey not in menukey_lst: menukey_lst.append(menukey)
for submenukey,submenuvalue in menuvalue.items():
if submenukey not in submenukey_lst: submenukey_lst.append(submenukey)
for index,mk in enumerate(menu.keys()):
for item in submenukey_lst:
menu[menukey_lst[index]]["lan1"] = language[selected_lan[0]][menukey_lst[index]]
menu[menukey_lst[index]]["lan2"] = language[selected_lan[1]][menukey_lst[index]]
menu[menukey_lst[index]]["scut"] = (scut[user[0]][mk])
print(menu)
Output
{'lbl01': {'id': 'file', 'lan1': 'கோப்பு', 'lan2': 'Hindi_File', 'scut': 'Ctrl+F'}, `'lbl02': {'id': 'accounts', 'lan1': 'கணக்கியல்', 'lan2': 'Hindi_accounts', 'scut': 'Shift+F5'}}`
This should work.
for key, value in menu.items():
for sub_key in value.keys():
if sub_key == 'lan1':
value[sub_key] = language[selected_lan[0]][key]
elif sub_key == 'lan2':
value[sub_key] = language[selected_lan[1]][key]
elif sub_key == 'scut':
value[sub_key] = scut[user[0]][key]
I append number of queries into a list and then filter the table using sqlachemies query function and or_. Table consists of warehouses, and I want to query them using names, available storage, prices and services. The logic should be correct but I get error
subquery must return only one column
#search.route('/search/filter', methods = ['POST'])
def filter():
name = request.form.get('name')
n_storage = request.form.get('n_storage')
#MIN PRICE MAX PRICE
min_p = request.form.get('min_p')
max_p = request.form.get('max_p')
#SERVICES
labelling = True if request.form.get('labelling') else False
manual_geo_data_entry = True if request.form.get('manual_geo_data_entry') else False
item_packaging = True if request.form.get('item_packaging') else False
palette_packaging = True if request.form.get('palette_packaging') else False
filters = []
if name:
filters.append(Warehouse.query.filter(Warehouse.name.match(name)))
if n_storage:
filters.append(Warehouse.query.filter(Warehouse.volume_available > n_storage))
#FILTERING BASED ON SERVICES
if labelling:
filters.append(Warehouse.query.filter(Warehouse.labelling.is_(True)))
if manual_geo_data_entry:
filters.append(Warehouse.query.filter(Warehouse.manual_geo_data_entry.is_(True)))
if item_packaging:
filters.append(Warehouse.query.filter(Warehouse.item_packaging.is_(True)))
if palette_packaging:
filters.append(Warehouse.query.filter(Warehouse.palette_packaging.is_(True)))
results = Warehouse.query.filter(or_(*filters)).all()
return render_template('search/search.html', title = 'Search', data = results)
sqlalchemy.exc.ProgrammingError: (psycopg2.errors.SyntaxError) subquery must return only one column
LINE 3: WHERE (SELECT "PilotApp_warehouse_test".id, "PilotApp_wareho...
^
[SQL: SELECT "PilotApp_warehouse_test".id AS "PilotApp_warehouse_test_id", "PilotApp_warehouse_test".name AS "PilotApp_warehouse_test_name", "PilotApp_warehouse_test".volume_available AS "PilotApp_warehouse_test_volume_available", "PilotApp_warehouse_test".volume_total AS "PilotApp_warehouse_test_volume_total", "PilotApp_warehouse_test".labelling AS "PilotApp_warehouse_test_labelling", "PilotApp_warehouse_test".manual_geo_data_entry AS "PilotApp_warehouse_test_manual_geo_data_entry", "PilotApp_warehouse_test".item_packaging AS "PilotApp_warehouse_test_item_packaging", "PilotApp_warehouse_test".palette_packaging AS "PilotApp_warehouse_test_palette_packaging", "PilotApp_warehouse_test".address AS "PilotApp_warehouse_test_address", "PilotApp_warehouse_test".email AS "PilotApp_warehouse_test_email", "PilotApp_warehouse_test".phone AS "PilotApp_warehouse_test_phone", "PilotApp_warehouse_test".owner AS "PilotApp_warehouse_test_owner"
FROM "PilotApp_warehouse_test"
WHERE (SELECT "PilotApp_warehouse_test".id, "PilotApp_warehouse_test".name, "PilotApp_warehouse_test".volume_available, "PilotApp_warehouse_test".volume_total, "PilotApp_warehouse_test".labelling, "PilotApp_warehouse_test".manual_geo_data_entry, "PilotApp_warehouse_test".item_packaging, "PilotApp_warehouse_test".palette_packaging, "PilotApp_warehouse_test".address, "PilotApp_warehouse_test".email, "PilotApp_warehouse_test".phone, "PilotApp_warehouse_test".owner
FROM "PilotApp_warehouse_test"
WHERE "PilotApp_warehouse_test".manual_geo_data_entry IS true) OR (SELECT "PilotApp_warehouse_test".id, "PilotApp_warehouse_test".name, "PilotApp_warehouse_test".volume_available, "PilotApp_warehouse_test".volume_total, "PilotApp_warehouse_test".labelling, "PilotApp_warehouse_test".manual_geo_data_entry, "PilotApp_warehouse_test".item_packaging, "PilotApp_warehouse_test".palette_packaging, "PilotApp_warehouse_test".address, "PilotApp_warehouse_test".email, "PilotApp_warehouse_test".phone, "PilotApp_warehouse_test".owner
FROM "PilotApp_warehouse_test"
WHERE "PilotApp_warehouse_test".item_packaging IS true)]
You should not pass to filter queries, but only conditions to avoid subqueries. I think it should work for you:
#search.route('/search/filter', methods = ['POST'])
def filter():
name = request.form.get('name')
n_storage = request.form.get('n_storage')
#MIN PRICE MAX PRICE
min_p = request.form.get('min_p')
max_p = request.form.get('max_p')
#SERVICES
labelling = True if request.form.get('labelling') else False
manual_geo_data_entry = True if request.form.get('manual_geo_data_entry') else False
item_packaging = True if request.form.get('item_packaging') else False
palette_packaging = True if request.form.get('palette_packaging') else False
filters = []
if name:
filters.append(Warehouse.name.match(name))
if n_storage:
filters.append(Warehouse.volume_available > n_storage)
#FILTERING BASED ON SERVICES
if labelling:
filters.append(Warehouse.labelling.is_(True))
if manual_geo_data_entry:
filters.append(Warehouse.manual_geo_data_entry.is_(True))
if item_packaging:
filters.append(Warehouse.item_packaging.is_(True))
if palette_packaging:
filters.append(Warehouse.palette_packaging.is_(True))
results = Warehouse.query.filter(or_(*filters)).all()
return render_template('search/search.html', title = 'Search', data = results)
I guess I am running into a beginner problem:
-> I want to loop over an array and insert the the values into lines of code that are executed.
For the attempt below I get "SyntaxError: can't assign to operator"
#Country-subsets (all countries in dataframe)
for s in country_filter:
s.lower() + '_immu_edu' = immu_edu.loc[immu_edu['CountryName'] == s]
Thanks for helping!
My expected output would be:
guinea_immu_edu = immu_edu.loc[immu_edu['CountryName'] == "Guinea"]
lao_immu_edu = immu_edu.loc[immu_edu['CountryName'] == "Lao PDR"]
bf_immu_edu = immu_edu.loc[immu_edu['CountryName'] == "Burkina Faso"]
us_immu_edu = immu_edu.loc[immu_edu['CountryName'] == "United States"]
ge_immu_edu = immu_edu.loc[immu_edu['CountryName'] == "Germany"]
Store your values in a dictionary and access using the keys:
my_dict = dict()
for s in country_filter:
my_dict[s.lower() + '_immu_edu'] = immu_edu.loc[immu_edu['CountryName'] == s]
this my code, i'm looking, is other way to code this in most efficient way?
i have multiple variables and inserted to the dictionary.
please feel to suggest and other options like array and etc will do.
def momentEndSpan(span_type,max_combo,length):
if "simply supported" == span_type:
q = max_combo
force = {}
RA = {"PA" : q*length/2}
RB = {"PB" : q*length/2}
RA_moment = {"MA" : 0}
R_mid_moment = {"Mmid": (q*math.pow(length,2))/8 }
RB_moment = { "MB" : 0}
force.update(RA)
force.update(RB)
force.update(RA_moment)
force.update(R_mid_moment)
force.update(RB_moment)
return force
elif "one end continuous" == span_type:
q = max_combo
x = (3/8)*length
force = {}
RA = {"Phinge" : 3*q*length/8}
RB = {"Pfixed" : 5*q*length/8}
RA_moment = {"Mhinge" : 0}
R_mid_moment = {"Mmid": (q*math.pow(length,2))*(9/128) }
RB_moment = { "MB" : -1*(q*math.pow(length,2))/8 }
force.update(RA)
force.update(RB)
force.update(RA_moment)
force.update(R_mid_moment)
force.update(RB_moment)
return force
Thank you very much
The "More Pythonic" way is to create one dictionary and update once.
q = max_combo
force = {}
if "simply supported" == span_type:
new = {"PA" : q*length/2,
"PB" : q*length/2,
"MA" : 0, "Mmid": (q*math.pow(length,2))/8,
"MB" : 0}
elif "one end continuous" == span_type:
x = (3/8)*length
new = {"Phinge" : 3*q*length/8,
"Pfixed" : 5*q*length/8,
"Mhinge" : 0,
"Mmid": (q*math.pow(length,2))*(9/128),
"MB" : -1*(q*math.pow(length,2))/8 }
force.update(new)
Also, note that if the force dictionary doesn't contain any previously defined items you can simply return the new and/or just continue to update the new in your next operations if there are any. Or just use name force instead of new.
q = max_combo
if "simply supported" == span_type:
force = {...}
elif "one end continuous" == span_type:
x = (3/8)*length
force = {...}
I would like to make a loop to create a dataframe that gathers the lines of an input dataframe, which have common points.
My problem : When I apply the function, the output dataframe is empty...
yet with a print (output) in the loop, we see that the program works .. I do not understand, i tried to change return position but that doesn't work
Thank you in advance for your help !
def group (dataframe, identifiant, output):
for i in range(len(identifiant)):
ident = identifiant.loc[i,"IDCTV"]
# print(ident)
for j in range(len(dataframe)):
if dataframe.loc[j,"IDCONTREVENANT"] == ident:
di = dataframe.loc[j, "DATE_INFRACTION"]
nt = dataframe.loc[j,"NOTRAIN"]
genre = dataframe.loc[j,"CODEETATCIVIL"]
age = dataframe.loc[j,"AGE"]
# print(di, nt, genre, age)
for k in range(len(dataframe)):
if k != j :
if dataframe.loc[k,"DATE_INFRACTION"] == di and dataframe.loc[k,"NOTRAIN"] == nt:
idgroup = dataframe.loc[k,"IDCONTREVENANT"]
genreidgroup = dataframe.loc[k,"CODEETATCIVIL"]
ageidgroup = dataframe.loc[k,"AGE"]
output = output.append({ "IDREF" : ident ,"CODEETATCIVILREF" : genre,"AGEREF" : age ,"IDCTV" : idgroup,"CODEETATCIVILCTV" : genreidgroup,"AGECTV" : ageidgroup}, ignore_index = True)
print(output)
return output
group(df,IDCTV,df_groups)
print(df_groups)
I think you want to change
group(df,IDCTV,df_groups)
to
df_groups = group(df,IDCTV,df_groups)
Right now you're calling the group funciton and doing all that calculation, but you're not saving the output anywhere. So when you run print(df_groups) it prints out whatever it was before you called the function.