I am trying workarounds for a discord command that modifies a document.
I am have a simple question: is it possible to update a whole column with something like sheet.update('B:B', scores) with a dictionary (multiple objects)? I want to have columns B and C updated with the keys being in B and values in C.
Before I had to use code specified in this post, and make two lists (one with the names [B] and one with the values [C]) with the names and values in their own lists, so they were nested.
for count in range(len(data['guild']['members'])): # For every guild member:
res = requests.get("https://playerdb.co/api/player/minecraft/" + data['guild']['members'][count]['uuid']) # Response from server
if res.status_code != 200: # If it wasn't a success, continue the loop and print a message
ctx.author.send("Error 1: Invaild name from player database API!")
continue
name = res.json()['data']['player']['username'] # We know it was successful if we got to this point, so it's safe to try and get data from our response
names.append(name)
# Members' GXP
xp = data['guild']['members'][count]['expHistory']
xp = sum(xp.values())
xpHist.append(xp)
# Weekly Total
wTotal = sum(xpHist)
print(xpHist)
That didn't work in the command and I am trying a dictionary method with the enumerate function.
Thanks!
EDIT: Updated to reference code as got striked for that :)
You can achieve the following with a simple for loop.
Add "Keys" to Cell A1 and "Values" to Cell B1.
Make a variable idx or anything and set it 2 as we already set A1 and B1 cell to "Keys" and "Values".
Iterate through dict.items() and update cell "A{idx}" to key and "B{idx}" to key and value respectively.
Add one to idx so while iterating to nth key and value, it does not update the same cell
sheet.update_cell("A1", "Keys")
sheet.update_cell("B1", "Values")
idx = 2
for k, v in dict.items():
sheet.update_cell(f"A{idx}", k)
sheet.update_cell(f"B{idx}", v)
idx += 1
Related
I have some code which is something along the lines of
storage = {}
for index, n in enumerate(dates):
if n in specific_dates:
for i in a_list:
my_dict[i] = {}
my_dict[i]["somthing"] = value
my_dict[i]["somthing2"] = value_2
else:
#print(storage[dates[index - 1]["my_dict"][i]["somthing"])
for i in a_list:
my_dict[i] = {}
my_dict[i][somthing] = different_value - storage[dates[index - 1]["my_dict"][i]["somthing"]
my_dict[i]["somthing2"] = different_value_2
storage[n]["my_dict"] = my_dict
The first pass will initiate the code in if n in specific_dates: the second pass goes to for i in a_list:
Essentially the code is getting a value set on specific dates and this value is then used for nonspecific dates that occur after the specific date until the next specific date overrides that value. However, at every date, i save a dictionary of values within a master dictionary called storage.
I found the problem which is when I print my_dict on the second pass my_dict[i] is literally an empty dictionary whereas prior to that loop it was filled. Where I have put the commented-out print line it would print value. I have fixed this by changing storage[n]["my_dict"] = my_dict to storage[n]["my_dict"] = my_dict.copy() and can now access value.
However, I do not really understand why this didnt work how I expected in the first place as I thought by assigning my_dict to storage it was creating new memory.
I was hoping someone could explain why this is happening and why storage[dates[index - 1]["my_dict"][i]["somthing"] doesn't create a new space in memory if that is indeed what is happening.
I am taking a user input of "components" splitting it into a list and comparing those components to a list of available components generated from column A of a google sheet. Then what I am attempting to do is return the cell value from column G corresponding the Column A index. Then repeat this for all input values.
So far I am getting the first value just fine but I'm obviously missing something to get it to cycle back and to the remaining user input components. I tried some stuff using itertools but wasn't able to get the results I wanted. I have a feeling I will facepalm when I discover the solution to this through here or on my own.
mix = select.split(',') # sets user input to string and sparates elements
ws = s.worksheet("Details") # opens table in google sheet
c_list = ws.col_values(1) # sets column A to a list
modifier = [""] * len(mix) # sets size of list based on user input
list = str(c_list).lower()
for i in range(len(mix)):
if str(mix[i]).lower() in str(c_list).lower():
for j in range(len(c_list)):
if str(mix[i]).lower() == str(c_list[j]).lower():
modifier[i] = ws.cell(j+1,7).value # get value of cell from Column G corresponding to Column A for component name
print(mix)
print(modifier)
You are over complicating the code by writing C like code.
I have changed all the loops you had to a simpler single loop, I have also left comments above each code line to explain what it does.
# Here we use .lower() to lower case all the values in select
# before splitting them and adding them to the list "mix"
mix = select.lower().split(",")
ws = s.worksheet("Details")
# Here we used a list comprehension to create a list of the "column A"
# values but all in lower case
c_list = [cell.lower() for cell in ws.col_values(1)]
modifier = [""] * len(mix)
# Here we loop through every item in mix, but also keep a count of iterations
# we have made, which we will use later to add the "column G" element to the
# corresponding location in the list "modifier"
for i, value in enumerate(mix):
# Here we check if the value exists in the c_list
if value in c_list:
# If we find the value in the c_list, we get the index of the value in c_list
index = c_list.index(value)
# Here we add the value of column G that has an index of "index + 1" to
# the modifier list at the same location of the value in list "mix"
modifier[i] = ws.cell(index + 1, 7).value
I want to append the key value pairs in my python dictionary without including the brackets... I'm not really sure how to do that.
I've tried looking at similar questions but it isn't working for me.
#this creates a new workbook call difference
file = xlrd.open_workbook('/Users/im/Documents/Exception_Cases/Orders.xls')
wb = xl_copy(file)
Sheet1 = wb.add_sheet('differences')
#this creates header for two columns
Sheet1.write(0,0,"S_Numbers")
Sheet1.write(0,1," Values")
#this would store all the of Key, value pair of my dictionary into their respective SO_Numbers, Booking Values column
print(len(diff_so_keyval))
rowplacement = 1
while rowplacement < len(diff_so_keyval):
for k, v in diff_so_keyval.items():
Sheet1.write(rowplacement,0,k)
Sheet1.write(rowplacement,1,str(v))
rowplacement = rowplacement + 1
#This is what I have in my diff_so_keyval dictionary
diff_so_keyval = {104370541:[31203.7]
106813775:[187500.0]
106842625:[60349.8]
106843037:[492410.5]
106918995:[7501.25]
106919025:[427090.0]
106925184:[30676.4]
106941476:[203.58]
106941482:[203.58]
106941514:[407.16]
106962317:[61396.36]}
#this is the output
S_numbers Values
104370541 [31203.7]
106813775 [187500.0]
106842625 [60349.8]
I want the values without the brackets
Looks to me like the 'values' in the dictionary are actually single-element lists.
If you simply extract the 0th element out of the list, then that should work for 'removing the brackets':
Sheet1.write(rowplacement, 1, v[0])
I have a list of ids and am trying to do some processing, using eq function on a dataframe object, on all but a particular element of the list. Can you please suggest me how it can be done?
ids = list(set(df['user_id']))
for k in ids:
#processing = df.user_id.eq(ids-{k}????)
One thing to watch out for this is that you don't want to be destructively modifying the ids list as you are looping through it to remove the current element. Thus, one way we can do this is to loop through the indexes and, for each index i, create a new spliced together list that contains all the elements in ids other than at index i. I would do it as such:
for i in range(len(ids)):
elemsExcludingi = ids[:i] + ids[i + 1:]
# use this list to do things
Good luck!
You can set an if statement in the for-loop, where target_id is the id you do not which to process
ids = list(set(df['user_id']))
for k in ids:
if k != target_id:
#processing code goes here
Use the keyword continue.
While in a loop whenever the keyword continue is called, it makes the loop to iterate over it leaving the code below unprocessed.
ids = list(set(df['user_id']))
for k in ids:
if k == 'the_element_you_dont_want':
continue #Skips the code below when its called
#Other code code block
#processing = df.user_id.eq(ids-{k}????)
I am currently attempting to write a Python 3 script that reads and manipulates Excel files to tell me how often a purchase in a particular place was made. For that I am using the openpyxl module.
My script currently automatically creates a dictionary for me that consists of a unique key for every store and how often it was purchased from.
It looks like this: {'Sains': 2, 'Sains Petrol': 1, 'McDonalds': 2, 'Council Tax': 1, 'Car Repair': 1, 'Steam Purchase': 1}
The next thing I would like to do is to write the name of every shop and the value of how often it was purchased from in cells that are next to each other, like so:
A3: Shop | number
A4: Shop | number
A5: Shop | number
Each shop and it's number is supposed to be in a new row.
The function to write to cell is new_sheet['A3'] = 'Hello World'. new_sheet is the name of the variable I assigned to the sheet.
I now want to write a piece of code that writes every shop and it's number to my new sheet.
I successfully managed to write a for-loop that lets me write a string to the cells on my sheet, but only as many times as there are entries in my dictionary.
The loop:
a = len(dict_shops_purchased_from)
for cell_number in range(2, a + 2):
cell = 'A' + str(cell_number)
for i in cell:
new_sheet[cell] = 'Hello World'
So this is going to write 'Hello World' into cells A3 to A8.
I also managed to write a for-loop that let's me make the dictionary's key and value into variables:
for key, value in dict_shops_purchased_from.items():
print(key, value)
My question is, how can I change the code so it will write the dictionary key in cell Ax and the value to cell Bx, because the problem is that
new_sheet[cell] comes from a for-loop and so do key and value
I tried the following:
for key, value in dict_shops_purchased_from.items():
print(key, value)
for cell_number in range(2, a + 2):
cell = 'A' + str(cell_number)
for i in cell:
new_sheet[cell] = key
But that only writes the last entry in the dictionary, which is 'Steam Purchase', six times
Any ideas how I could make this work?
I hope this makes sense
cell_no = 2
for key, value in dict_shops_purchased_from.items():
new_sheet['A' + str(cell_no)] = key
new_sheet['B' + str(cell_no)] = value
cell_no += 1
can you try above code, hope this helps