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
Related
I have been trying to figure out what the issue is and can't seem to figure it out.
valueRange = [j.value for i in copyRange for j in i]
vrCounter = 0
vrStep = 7
x.field_names = ["Jurisdiction","SPOC-Name", "Lines of Business","Market Area", "Consultant Personal Lines", "Consultant Business Lines", " ROC-Name"]
for i in range(0,len(valueRange)):
x.add_row(valueRange[i], valueRange[i+1], valueRange[i+2], valueRange[i+3], valueRange[i+4], valueRange[i+5], valueRange[i+6])
print(x)
I ran the code without the x.add_row() function and it printed the values correctly. The valueRange list is just a bunch of keywords that match the field_names.
As shown in the docs, add_row() takes a list of values as an argument.
Enclose all the values in a list and it must work.
x.add_row([valueRange[i], valueRange[i+1], valueRange[i+2], valueRange[i+3], valueRange[i+4], valueRange[i+5], valueRange[i+6]])
Turn out the issue was the for i in range(0,len(valueRange)): portion. So it wasn't possible to answer this question without complete information about that valueRange list. This list contained 28 (0-27) string values. The loop was stepping through the 0-27 range 1 at a time while trying to apply an i+number value to each one. This would quickly go out of bounds unless the step size matches the valueRange list.
The final solution looks like:
for i in range(0,len(valueRange),7):
x.add_row(valueRange[i:i+7])
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?
I am facing an 'List Index out of range' error when trying to iterate a for-loop over a table I've created from a CSV extract, but cannot figure out why - even after trying many different methods.
Here is the step by step description of how the error happens :
I'm removing the first line of an imported CSV file, as this
line contains the columns' names but no data. The CSV has the following structure.
columnName1, columnName2, columnName3, columnName4
This, is, some, data
I, have, in, this
very, interesting, CSV, file
After storing the CSV in a first array called oldArray, I want to populate a newArray that will get all values from oldArray but not the first line, which is the column name line, as previously
mentioned. My newArray should then look like this.
This, is, some, data
I, have, in, this
very, interesting, CSV, file
To create this newArray, I'm using the following code with the append() function.
tempList = []
newArray = []
for i in range(len(oldArray)):
if i > 0: #my ugly way of skipping line 0...
for j in range(len(oldArray[0])):
tempList.append(oldArray[i][j])
newArray.append(tempList)
tempList = []
I also stored the columns in their own separate list.
i = 0
for i in range(len(oldArray[0])):
my_columnList[i] = oldArray[0][i]
And the error comes up next : I now want to populate a treeview table from this newArray, using a for-loop and insert (in a function). But I always get the 'Index List out of range error' and I cannot figure out why.
def populateTable(my_tree, newArray, my_columnList):
i = 0
for i in range(len(newArray)):
my_tree.insert('','end', text=newArray[i][0], values = (newArray[i][1:len(newArray[0]))
#(im using the text option to bypass treeview's column 0 problem)
return my_tree
Error message --> " File "(...my working directory...)", line 301, in populateTable
my_tree.insert(parent='', index='end', text=data[i][0], values=(data[i][1:len(data[0])]))
IndexError: list index out of range "
Using that same function with different datasets and columns worked fine, but not for this here newArray.
I'm fairy certain that the error comes strictly from this 'newArray' and is not linked to another parameter.
I've tested the validity of the columns list, of the CSV import in oldArray through some print() functions, and everything seems normal - values, row dimension, column dimension.
This is a great mystery to me...
Thank you all very much for your help and time.
You can find a problem from your error message: File "(...my working directory...)", line 301, in populateTable my_tree.insert(parent='', index='end', text=data[i][0], values=(data[i][1:len(data[0])])) IndexError: list index out of range
It means there is an index out of range in line 301: data[i][0] or data[i][1:len(data[0])]
(i is over len(data)) or (0 or 1 is over len(data[0]))
My guess is there is some empty list in data(maybe data[-1]?).
if data[i] is [] or [some_one_item], then data[i][1:len(data[0])] try to access to second item which not exists.
there is no problem in your "ugly" way to skip line 0 but I recommend having a look on this way
new_array = old_array.copy()
new_array.remove(new_array[0])
now for fixing your issue
looks like you have a problem in the indexing
when you use a for loop using the range of the length of an array you use normal indexing which starts from one while you identify your i variable to be zero
to make it simple
len(oldArray[0])
this is equal to 4 so when you use it in the for loop it's just like saying
for i in range(4):
to fix this you can either subtract 1 from the length of the old array or just identify the i variable to be 1 at the first
i = 1
for i in range(len(oldArray[0])):
my_columnList[i] = oldArray[0][i]
or
i = 0
for i in range(len(oldArray[0])-1):
my_columnList[i] = oldArray[0][i]
this mistake is also repeated in your populateTree function
so in the same way your code would be
def populateTree(my_tree, newArray, my_columnList):
i = 0
for i in range(len(newArray)-1):
my_tree.insert('','end', text=newArray[i][0], values = (newArray[i][1:len(newArray[0]))
#(im using the text option to bypass treeview's column 0 problem)
return my_tree
I'm trying to put a for loop inside of a dict. (See my code bellow)
tempdict["data"] = {
"id": words[0],
for j in range(1, 100):
tempdict[fieldnames[j]] = words[j]
}
So, I'm reading out of a CSV file and converting it to JSON. (This is to automate a process at work)
Not sure if there is anything else to add, just ask if you need to know more.
I would appreciate any help I can get :)
so, extra context:
I'm trying to map the value from the CSV file to the dict with the key as one of the fieldnames (See fieldnames bellow)
fieldnames = ["id", "subscriber-A-01", "subscriber-A-02", "subscriber-A-03", "subscriber-A-04", "subscriber-A-05", "subscriber-A-06", "subscriber-A-07", "subscriber-A-08", "subscriber-A-09", "subscriber-A-10", "subscriber-B-01", "subscriber-B-02", "subscriber-B-03", "subscriber-B-04", "subscriber-B-05", "subscriber-B-06", "subscriber-B-07", "subscriber-B-08", "subscriber-B-09", "subscriber-B-10", "subscriber-C-01", "subscriber-C-02", "subscriber-C-03", "subscriber-C-04", "subscriber-C-05", "subscriber-C-06", "subscriber-C-07", "subscriber-C-08", "subscriber-C-09", "subscriber-C-10", "subscriber-D-01", "subscriber-D-02", "subscriber-D-03", "subscriber-D-04", "subscriber-D-05", "subscriber-D-06", "subscriber-D-07", "subscriber-D-08", "subscriber-D-09", "subscriber-D-10", "subscriber-E-01", "subscriber-E-02", "subscriber-E-03", "subscriber-E-04", "subscriber-E-05", "subscriber-E-06", "subscriber-E-07", "subscriber-E-08", "subscriber-E-09", "subscriber-E-10", "subscriber-F-01", "subscriber-F-02", "subscriber-F-03", "subscriber-F-04", "subscriber-F-05", "subscriber-F-06", "subscriber-F-07", "subscriber-F-08", "subscriber-F-09", "subscriber-F-10", "subscriber-G-01", "subscriber-G-02", "subscriber-G-03", "subscriber-G-04", "subscriber-G-05", "subscriber-G-06", "subscriber-G-07", "subscriber-G-08", "subscriber-G-09", "subscriber-G-10", "subscriber-H-01", "subscriber-H-02", "subscriber-H-03", "subscriber-H-04", "subscriber-H-05", "subscriber-H-06", "subscriber-H-07", "subscriber-H-08", "subscriber-H-09", "subscriber-H-10", "subscriber-I-01", "subscriber-I-02", "subscriber-I-03", "subscriber-I-04", "subscriber-I-05", "subscriber-I-06", "subscriber-I-07", "subscriber-I-08", "subscriber-I-09", "subscriber-I-10", "subscriber-J-01", "subscriber-J-02", "subscriber-J-03", "subscriber-J-04", "subscriber-J-05", "subscriber-J-06", "subscriber-J-07", "subscriber-J-08", "subscriber-J-09", "subscriber-J-10", "DISPLAY_TYPE", "stationCode"]
So, from subscriber-A-1 to subscriber-J-10 should be mapped to value 1 to 100 of the CSV file.
Update
This is how I made it work.
tempdict["data"] = dict(zip(fieldnames[1:100], words[1:100]))
tempdict["data"].update({"DISPLAY_TYPE": words[102]})
Thank you all for the help!
You can pair the sliced list of keys and the sliced list of values with zip and pass the zipped pairs to the dict constructor to build the desired dict instead:
tempdict['data'] = dict(zip(fieldnames[:101], words[:101]))
How do you get the very next list within a nested list in python?
I have a few lists:
charLimit = [101100,114502,124602]
conditionalNextQ = [101101, 101200, 114503, 114504, 124603, 124604]`
response = [[100100,4]
,[100300,99]
,[1100500,6]
,[1100501,04]
,[100700,12]
,[100800,67]
,[100100,64]
,[100300,26]
,[100500,2]
,[100501,035]
,[100700,9]
,[100800,8]
,[101100,"hello"]
,[101101,"twenty"] ... ]
for question in charLimit:
for limitQuestion in response:
limitNumber = limitQuestion[0]
if question == limitNumber:
print(limitQuestion)
The above code is doing what I want, i.e. printing the list instances in response when it contains one of the numbers in charlimit. However, I also want it to print the immediate next value in response also.
For example the second-to-last value in response contains 101100 (a value thats in charlimit) so I want it to not only print
101100,"hello"
(as the code does at the moment)
but the very next list also (and only the next)
101100,"hello"
101101,"twenty"
Thank is advance for any help here. Please note that response is a verrrrry long list and so I'm looking to make things fairly efficient if possible, although its not crucial in the context of this work. I'm probably missing something very simple but cant find examples of anyone doing this without using specific indexes in very small lists.
You can use enumerate
Ex:
charLimit = [101100,114502,124602]
conditionalNextQ = [101101, 101200, 114503, 114504, 124603, 124604]
response = [[100100,4]
,[100300,99]
,[1100500,6]
,[1100501,04]
,[100700,12]
,[100800,67]
,[100100,64]
,[100300,26]
,[100500,2]
,[100501,035]
,[100700,9]
,[100800,8]
,[101100,"hello"]
,[101101,"twenty"]]
l = len(response) - 1
for question in charLimit:
for i, limitQuestion in enumerate(response):
limitNumber = limitQuestion[0]
if question == limitNumber:
print(limitQuestion)
if (i+1) <= l:
print(response[i+1])
Output:
[101100, 'hello']
[101101, 'twenty']
I would eliminate the loop over charLimit and loop over response instead. Using enumerate in this loop allows us to access the next element by index, in the case that we want to print it:
for i, limitQuestion in enumerate(response, 1):
limitNumber = limitQuestion[0]
# use the `in` operator to check if `limitNumber` equals any
# of the numbers in `charLimit`
if limitNumber in charLimit:
print(limitQuestion)
# if this isn't the last element in the list, also
# print the next one
if i < len(response):
print(response[i])
If charLimit is very long, you should consider defining it as a set instead, because sets have faster membership tests than lists:
charLimit = {101100,114502,124602}