I have a for loop that cycles through and creates 3 data frames and stores them in a dictionary. From each of these data frames, I would like to be able to create another dictionary, but I cant figure out how to do this.
Here is the repetitive code without the loop:
Trad = allreports2[allreports2['Trad'].notna()]
Alti = allreports2[allreports2['Alti'].notna()]
Alto = allreports2[allreports2['Alto'].notna()]
Trad_dict = dict(zip(Trad.State, Trad.Position))
Alti_dict = dict(zip(Alti.State, Alti.Position))
Alto_dict = dict(zip(Alto.State, Alto.Position))
As stated earlier, I understand how to make the 3 dataframes by storing them in a dictionary and I understand what needs to go on the right side of the equal sign in the second statement in the for loop, but not what goes on the left side (denoted below as XXXXXXXXX).
Routes = ['Trad', 'Alti', 'Alto']
dfd = {}
for route in Routes:
dfd[route] = allreports2[allreports2[route].notna()]
XXXXXXXXX = dict(zip(dfd[route].State, dfd[route].Position))
(Please note: I am very new to Python and teaching myself so apologies in advance!)
This compromises readability, but this should work.
Routes = ['Trad', 'Alti', 'Alto']
dfd, output = [{},{}] # Unpack List
for route in Routes:
dfd[route] = allreports2[allreprots2[route].notna()]
output[route] = dict(zip(dfd[route].State, dfd[route].Position))
Trad_dict, Alti_dict, Alto_dict = list(output.values()) # Unpack List
Reference
How can I get list of values from dict?
Related
I'm currently trying to get into Python and Ren'Py a bit. Since I like to design a lot dynamically
and don't want to use copy&paste so often, I'm trying to create a page that will have ImageButtons with the corresponding number I specify.
In the example below I use "4" - but this can be higher.
I have built a class for this purpose:
Example:
init python:
class PictureSettings(object):
def __init__ (self, ImgIdle, ImgHover, LabelCall):
self.ImgIdle = ImgIdle
self.ImgHover = ImgHover
self.LabelCall = LabelCall
return
For the Idle/Hover and for the Jump.
If I insert in the code now in an object each entry "manually" with append I get all 4 pictures as desired indicated.
Example: (Works - but is not dynamic)
python:
var_pictures = []
var_pictures.append(PictureSettings("img_picture_1_idle", "img_picture_1_hover", "picture_1"))
var_pictures.append(PictureSettings("img_picture_2_idle", "img_picture_2_hover", "picture_2"))
var_pictures.append(PictureSettings("img_picture_3_idle", "img_picture_3_hover", "picture_3"))
var_pictures.append(PictureSettings("img_picture_4_idle", "img_picture_4_hover", "picture_4"))
I would like it to be like this:
Example (Here I get only ""img_picture_4_idle", "img_picture_4_hover", "picture_4""):
$ countlimit = 4
$ count = 1
python:
while count < countlimit:
var_pictures = []
var_pictures.append(PictureSettings(
ImgIdle = "img_picture_[count]_idle",
ImgHover = "img_picture_[count]_hover",
LabelCall = "picture_[count]"))
count += 1
Have already tried various things, unfortunately without success.
For example: with Add - instead of append (because this overwrites the result and leaves only the last entry
I get the following error:
var_pictures.add(PictureSettings( AttributeError: 'RevertableList' object has no attribute 'add')
Maybe someone can help me with the solution so I can keep my code dynamic without copying something X times.
Thanks for your help
You are creating your list inside your loop, so it is recreated every time.
At the end, you only get the last created list.
var_pictures = []
while count < countlimit:
var_pictures.append(PictureSettings(
ImgIdle = "img_picture_[count]_idle",
ImgHover = "img_picture_[count]_hover",
LabelCall = "picture_[count]"))
count += 1
On another subject, if you want to do this in a more pythonic way:
pictures = [] # no need for var_, we know its a variable
for i in range(1, 5):
pictures.append(PictureSettings(
# in python, we prefere snake_case attributes
img_idle=f'img_picture_{i}_idle',
img_hover=f'img_picture_{i}_hover',
...
))
# or even shorter with list comprehension
pictures = [
PictureSettings(
img_idle=f'img_picture_{i}_idle',
)
for i in range(1, 5)
]
By the way, no need to return in your class constructor
The title may sound confusing...but this is what I need to do:
I have a list (which will be variable in length, with different values depending on various scenarios), e.g: list1 = ['backup', 'downloadMedia', 'createAlbum']. From this list, I need to create one of the following for each of these items: (and obviously the name will update depending on the item in the list)
I need to create a new list called: testcases_backup = []
I need to create a new list called: results_backup = []
I need to create a new list called: screenshot_paths_backup = []
And lastly, I need to open a new worksheet, which requires: worksheet1 = workbook.add_worksheet('Results'). Of note in this case, I will need to iterate 1,2,3,... for the worksheet name for each of the items in the list. So for the first iteration for 'backup', it will be worksheet1. and 2 for downloadMedia, etc.
I have tried using dictionaries, but at this point I am not making any real progress.
My attempt: (I have very limited exp with dictionaries)
master_test_list = ['backup', 'downloadMedia', 'createAlbum']
master_test_dict = {}
def addTest(test, worksheet, testcases_list, results_list, screenshots_path_list):
master_test_dict[test] = worksheet
master_test_dict[test] = testcases_list
master_test_dict[test] = results_list
master_test_dict[test] = screenshots_path_list
for test in master_test_list:
addTest(test, "worksheet"+str(master_test_list.index(test)+1), "testcases_list_"+test, "results_list_"+test, "screenshots_path_list_"+test)
print(results_list_backup)
I thought this might work...but I just get strings inside the lists, and so I cannot define them as lists:
worksheets = []
for i in range(len(master_test_list)):
worksheets.append(str(i+1))
worksheets = ["worksheet%s" % x for x in worksheets]
testcases = ["testcases_list_%s" % x for x in master_test_list]
results = ["results_%s" % x for x in master_test_list]
screenshot_paths = ["screenshot_paths_%s" % x for x in master_test_list]
for w in worksheets:
w = workbook.add_worksheet('Results')
for t in testcases:
t = []
for r in results:
r = []
for s in screenshot_paths:
s = []
Adding a second answer since the code is significantly different, addressing the specified request for how to create n copies of lists:
def GenerateElements():
# Insert your code which generates your list here
myGeneratedList = ['backup', 'downloadMedia', 'createAlbum']
return myGeneratedList
def InitDict(ListOfElements):
# Dont make a new free floating list for each element of list1. Generate and store the lists you want in a dictionary
return dict([[x, []] for x in ListOfElements])
def RunTest():
for myContent in list1:
# Do whatever you like to generate the data u need
myTestCaseList = ['a', 'b']
myResultsList = [1, 2]
myScreenshot_Paths_List = ['sc1', 'sc2']
# 1 Store your created list for test case of item 'myContent' from list1 in a dictionary
testcases[myContent].append(myTestCaseList)
# 2 Same but your results list
results[myContent].append(myResultsList)
# 3 Same but your screenshot_paths list
screenshot_paths[myContent].append(myScreenshot_Paths_List)
# 4 Make an excel sheet named after the item from list1
# run_vba_macro("C:\\Users\\xx-_-\\Documents\\Coding Products\\Python (Local)\\Programs\\Python X Excel\\AddSheets.xlsm","SheetAdder", "AddASheet", myContent)
list1 = GenerateElements()
testcases, results, screenshot_paths = InitDict(
list1), InitDict(list1), InitDict(list1)
NumTests = 5 # Number of tests you want
for x in range(NumTests):
RunTest()
What's going on here is just defining some initialization functions and then exercising them in a couple of lines.
My understanding is that you are running a series of tests, where you want a list of the inputs and outputs to be a running tally kind of thing. As such, this code uses a dictionary to store a list of lists. The dictionary key is how you identify which log you're looking at: test cases log vs results log vs screenshot_paths log.
As per my understanding of your requirements, each dictionary element is a list of lists where the 1st list is just the output of the first test. The second list is the first with the outcome of the second test/result appended to it. This goes on, so the structure looks like:
testcases= [ [testcase1] , [testcase1,testcase2] , [testcase1,testcase2,testcase3] ]
etc.
If this isn't exactly what you want you can probably modify it to suit your needs.
You explanation leaves some things to be imagined, but I think I've got what you need. There are two files: The .py python file and an excel file which is the spreadsheet serving as a foundation for adding sheets. You can find the ones I made on my github:
https://github.com/DavidD003/LearningPython
here is the excel code. Sharing first because its shorter. If you don't want to download mine then make a sheet called 'AddSheets.xlsm' with a module called 'SheetAdder' and within that module put the following code:
Public Sub AddASheet(nm)
Application.DisplayAlerts = False 'Reset on workbook open event, since we need it to be False here right up to the point of saving and closing
Dim NewSheet As Worksheet
Set NewSheet = ThisWorkbook.Sheets.Add
NewSheet.Name = nm
End Sub
Make sure to add this to the 'ThisWorkbook' code in the 'MicroSoft Excel Objects' folder of the VBA project:
Private Sub Workbook_Open()
Application.DisplayAlerts = True
End Sub
The python script is as follows:
See [this question][1] for an example of how to type format the filepath as a string for function argument. I removed mine here.
import win32com.client as wincl
import os
# Following modified from https://stackoverflow.com/questions/58188684/calling-vba-macro-from-python-with-unknown-number-of-arguments
def run_vba_macro(str_path, str_modulename, str_macroname, shtNm):
if os.path.exists(str_path):
xl = wincl.DispatchEx("Excel.Application")
wb = xl.Workbooks.Open(str_path, ReadOnly=0)
xl.Visible = True
xl.Application.Run(os.path.basename(str_path)+"!" +
str_modulename+'.'+str_macroname, shtNm)
wb.Save()
wb.Close()
xl.Application.Quit()
del xl
# Insert your code which generates your list here
list1 = ['backup', 'downloadMedia', 'createAlbum']
# Dont make a new free floating list for each element of list1. Generate and store the lists you want in a dictionary
testcases = dict([[x, []] for x in list1])
results = dict([[x, []] for x in list1])
screenshot_paths = dict([[x, []] for x in list1])
for myContent in list1:
myTestCaseList = [] # Do whatever you like to generate the data u need
myResultsList = []
myScreenshot_Paths_List = []
# 1 Store your created list for test case of item 'myContent' from list1 in a dictionary
testcases[myContent].append(myTestCaseList)
# 2 Same but your results list
results[myContent].append(myResultsList)
# 3 Same but your screenshot_paths list
screenshot_paths[myContent].append(myScreenshot_Paths_List)
# 4 Make an excel sheet named after the item from list1
run_vba_macro("C:\\Users\\xx-_-\\Documents\\Coding Products\\Python (Local)\\Programs\\Python X Excel\\AddSheets.xlsm",
"SheetAdder", "AddASheet", myContent)```
I started working on this before you updated your question with a code sample, so bear in mind I haven't looked at your code at all lol. Just ran with this.
Here is a summary of what all of the above does:
-Creates an excel sheet with a sheet for every element in 'list1', with the sheet named after that element
-Generates 3 dictionaries, one for test cases, one for results, and one for screenshot paths, where each dictionary has a list for each element from 'list1', with that list as the value for the key being the element in 'list1'
[1]: https://stackoverflow.com/questions/58188684/calling-vba-macro-from-python-with-unknown-number-of-arguments
I have a list adImageList of dictionary items in following form:
[{'Image_thumb_100x75': 'https://cache.domain.com/mmo/7/295/170/227_174707044_thumb.jpg',
'Image_hoved_400x300': 'https://cache.domain.com/mmo/7/295/170/227_174707044_hoved.jpg',
'Image_full_800x600': 'https://cache.domain.com/mmo/7/295/170/227_174707044.jpg'},
{'Image_thumb_100x75': 'https://cache.domain.com/mmo/7/295/170/227_1136648194_thumb.jpg',
'Image_hoved_400x300': 'https://cache.domain.com/mmo/7/295/170/227_1136648194_hoved.jpg',
'Image_full_800x600': 'https://cache.domain.com/mmo/7/295/170/227_1136648194.jpg'},
{'Image_thumb_100x75': 'https://cache.domain.com/mmo/7/295/170/227_400613427_thumb.jpg',
'Image_hoved_400x300': 'https://cache.domain.com/mmo/7/295/170/227_400613427_hoved.jpg',
'Image_full_800x600': 'https://cache.domain.com/mmo/7/295/170/227_400613427.jpg'}]
I have iterator which suppose to add local URL under each image record after fetching it from web (fetching part works ok). So I'm using following code to append local URL to existing dictionary items:
for i, d in enumerate(adImageList):
file_name_thumb = '0{}_{}_{}'.format(i, page_title,'_thumb_100x75.jpg')
urllib.request.urlretrieve(d['Image_thumb_100x75'], file_name_thumb)
local_path_thumb = dir_path+file_name_thumb
adImageList.insert[i](1,{'Image_thumb_100x75_local_path_thumb':local_path_thumb}) # not working
file_name_hoved = '0{}_{}_{}'.format(i, page_title,'_hoved_400x300.jpg')
urllib.request.urlretrieve(d['Image_hoved_400x300'], file_name_hoved)
local_path_hoved = dir_path+file_name_hoved
adImageList.insert[i](3,{'Image_hoved_400x300_local_path_hoved':local_path_hoved}) # not working
file_name_full = '0{}_{}_{}'.format(i, page_title,'_full_800x600.jpg')
urllib.request.urlretrieve(d['Image_full_800x600'], file_name_full)
local_path_full = dir_path+file_name_full
adImageList.insert[i](5,{'Image_full_800x600_local_path_full':local_path_full}) # not working
Idea is to extend dict items in following manner which also explains numbers 1,3 and 5 in my code
{'Image_thumb_100x75': 'https://cache.domain.com/mmo/7/295/170/227_174707044_thumb.jpg',
'Image_thumb_100x75_local_path_thumb':local_path_thumb #1,
'Image_hoved_400x300': 'https://cache.domain.com/mmo/7/295/170/227_174707044_hoved.jpg',
'Image_hoved_400x300_local_path_hoved':local_path_hoved #3
'Image_full_800x600': 'https://cache.domain.com/mmo/7/295/170/227_174707044.jpg',
'Image_full_800x600_local_path_full':local_path_full #5}
But it's giving me error:
TypeError: 'builtin_function_or_method' object is not subscriptable
Most likely here's what you had in mind:
adImageList[i]['Image_thumb_100x75_local_path_thumb']=local_path_thumb
This adds key 'Image_thumb_100x75_local_path_thumb' to the ith dictionary on the list and sets its value to local_path_thumb. The purpose of 1,3,5 is still unclear.
python stack traces give line numbers for a reason, but my guess is this line:
adImageList.insert[i]
insert is a method
I want to put entry data to the list of dictionaries to create a simple data base
I couldn't find adequate information about working with dictionaries in array.
workerspass = [{"someKey_2":"a"}, {"someKey_3":"b"}, {"somekey_1":"a"}]
def publish():
global workerspass
x = entry.get()#login
y = entryy.get()#password
#how to include that data in array list "workerspass'?
identif = int(identer.get())#checks if this id exists in the array.
Expected: I want entry from register to be stored in the dictionaries which is located in array. So basically I want to create basic registration system for entries.
Whole file available at: https://pastebin.com/Tij0dnb9
userspass = {
'user1':'pass1',
'user2':'pass2',
'user3':'pass3'
} #define dictionary like this
def validate_user(database,username,password):
if (username, password) in database.items():
return 1
else:
return 0
print(validate_user(userspass,'user1','pass1'))
print(validate_user(userspass,'user1','pass3'))
results:
1
0
I think this will suffice for your need. Let me know if you have any questions. :)
I am getting my feet wet with Python. I never done any programming or what so ever before and I really would appreciate it if someone would explain his_hers answer and not just post it since I want to learn something! Even better would be not posting the answere, but just giving hints what I should look at or something :)
I have several lists with a lot of values (numbers) one the one side.
On the other side, I have a URL which needs to be updated by the numbers out of the several lists and then be saved into another list for further process.
#borders of the bbox
longmax = 15.418483 #longitude top right
longmin = 4.953142 #longitude top left
latmax = 54.869808 #latitude top
latmin = 47.236219 #latitude bottom
#longitude
longstep = longmax - longmin
longstepx = longstep / 100 #longitudal steps the model shall perfom
#latitude
latstep = latmax - longmin
latstepx = latstep / 100 #latitudal steps the model shall perform
#create list of steps through coordinates longitude
llong = []
while longmin < longmax:
longmin+=longstepx
llong.append(+longmin)
#create list of steps through coordinates latitude
llat = []
while latmin < latmax:
latmin+=latstepx
llat.append(+latmin)
#create the URLs and store in list
for i in (llong):
"https://api.flickr.com/services/rest/?method=flickr.photos.search&format=json&api_key=5....lback=1&page=X&per_page=500&bbox=i&accuracy=1&has_geo=1&extras=geo,tags,views,description",sep="")"
As you can see, I try to make a request to the REST API from flickr.
What I dont understand is:
How do I get the loop to go through my lists, insert the values from the list to a certain point in the URL?
How to I tell the loop to save each URL separately after it inserted the first number out of list "llong" and "llat" and then proceed with the two next numbers.
Any hints?
You can use string formatting to insert whatever you want into your url:
my_list=["foo","bar","foobar"]
for word in my_list:
print ("www.google.com/{}".format(word))
www.google.com/foo
www.google.com/bar
www.google.com/foobar
The {} is used in your string wherever you want to insert.
To save them to a list you can use zip, insert using string formatting and then append to a new list.
urls=[]
for lat,lon in zip(llat,llong):
urls.append("www.google.com/{}{}".format(lat,lon))
Python string formatting: % vs. .format
I think the .format() method is the preferred method as opposed to using the "www.google.com/%s" % lat syntax.
There are answers here that discuss some of the differences.
The zip function is best explained with an example:
Say we have 2 lists l1 and l2:
l1 = [1,2,3]
l2 = [4,5,6]
If we use zip(l1,l2)the result will be:
[(1, 4), (2, 5), (3, 6)]
Then when we loop over the two zipped lists like below:
for ele_1,ele_2 in zip(l1,l2):
first iteration ele_1 = 1, ele_2 = 4
second iteration ele_1 = 2 ele_2 = 5 and so on ...
myUrls=[]
for i in range len(llat) # len(llong) is valid if both have same size.
myUrls.append(newUrl(llat[i]),llong[i])
def newUrl(lat,long):
return "www.flickr.......lat="+lat+".....long="+long+"...."