I'm trying to create a variable with multiple numbers which is then parsed into a code to delete multiple rows via Smartsheet API.
This is how it works:
smartsheet_client.Sheets.delete_rows(
3637721312342212, #sheet_id
[567387105060740, 4908041578801028]) #row_id
I would like to parse multiple numbers by assigning it to a variable beforehand, but it doesn't work. I wonder if the brackets are the problem when parsing the variable.
row_ids = 567387105060740, 4908041578801028
print(row_ids)
(567387105060740, 4908041578801028)
smartsheet_client.Sheets.delete_rows(
3637721312342212, #sheet_id
[row_ids]) #row_id
If I get the variable to work, I wonder how to transform all the values of one column (example below) into the same format to create a variable with the respective numbers.
From:
0 4738432649193348
1 5625432649192019
2 6321432649125716
Name: row_id_column, dtype: Int64
To (I guess tuple):
row_id_column = 4738432649193348, 5625432649192019, 6321432649125716
The .delete_rows() function requires a list of row ids (integers).
row_ids = 567387105060740, 4908041578801028
The above will create a tuple with the row ids. Instead, you need:
row_ids = [567387105060740, 4908041578801028]
From here, your code should look like:
row_ids = [567387105060740, 4908041578801028]
smartsheet_client.Sheets.delete_rows(
3637721312342212, #sheet_id
row_ids) # list of row ids
Note the removed []. Your current method [row_id] will send a list of tuples [(567387105060740, 4908041578801028)] instead of the required list of integers.
Related
I have the following code
import datetime
Date_0 = [datetime.date(2021,3,10), datetime.date(2021,3,11)]
Date_1 = datetime.date(2021,3,12)
Date_combine = [Date_0, Date_1]
I got the result of Data_combine: [[2021-03-10, 2021-03-11], 2021-03-12]
But I want to get this: [2021-03-10, 2021-03-11, 2021-03-12]
How could I achieve this? Thank you!
Just make a new list that unpacks the existing list and adds on the new element:
Date_combine = [*Date_0, Date_1]
The * says "unpack the contents of Date_0 here without the wrapping" (see PEP 448 for details). Put *s before any element that is itself a list or other iterable and you want to include the contents of, leave it off for the values you want to include as themselves, without unpacking.
On older Python (pre-3.5), you could use concatenation for a simple case like this, by wrapping the non-list elements in temporary lists e.g.:
Date_combine = Date_0 + [Date_1]
or if you don't need it to be a new list, and modifying Date_0 in place is fine, the even simpler:
Date_0.append(Date_1)
I have two values number and sys_id. I have made seperate list for both of the values. How can save it in any other data structure like dictionary, or something else because i those list of number and sys_id are related. I am doing it in Python
Below Is the code what i have done
ticket_num.append(resp['result'][idx]['number'])
sys_id.append(resp['result'][idx]['sys_id']) ```
This is making two list one for ticket_num and sys_id. As Ticket number and sys_id are related for example ticket_num = ['INC00012','INC00013','INC00014' ] ,
sys_id = ['644323432sfasesdf213', '644323432dfgdfkdskrwwr', 'f283044423fdldsf09']
As this list are related like ticket_num[0] is directly link with sys_id[0]
So can i make a dictionary that contains ticket_num, sys_id directly without creating lists(for e.g. : {ticket_num : '...' , sys_id = '....' , ..... }
Use zip with dict
Ex:
ticket_num = ['INC00012','INC00013','INC00014' ]
sys_id = ['644323432sfasesdf213', '644323432dfgdfkdskrwwr', 'f283044423fdldsf09']
print(dict(zip(ticket_num, sys_id)))
Output:
{'INC00012': '644323432sfasesdf213',
'INC00013': '644323432dfgdfkdskrwwr',
'INC00014': 'f283044423fdldsf09'}
Welcome to Stackoverflow.
Do you actually need the lists of ticket numbers and IDs? If not that you could instead consider building the structure you need instead of the lists.
You don't say whether you want to be able to look up IDs from ticket numbers or vice versa. This solution allows you to do either:
idx_from_ticket = {}
ticket_from_idx = {}
# In the loop that produces the values, instead of the current appends ...
temp = resp['result'][idx]
idx = temp['sys_id]
number = temp['number']
idx_from_ticket[number] = idx
ticket_from_idx[idx] = number
The two dictionaries can then be used to correlate the IDs and ticket numbers. If you want to actually do something else then I hope this code gives you enough clues.
If you do already have the lists and want to retain them then the zip function is your friend.
idx_from_ticket = dict(zip(ticket_num, sys_id))
ticket_from_idx = dict(zip(sys_id, ticket_num))
zip, when called with two argument, yields a sequence of two-element tuples, which the
dict function assumes are key/value pairs.
I have list like below.
test = ['firstvalue', 'thirdvalue']
I want to insert the some values to the list.
secondvalue at index 1 and fourthvalue at index 3
so the output list looks like below
test = ['firstvalue', 'secondvalue', 'thirdvalue', 'fourthvalue']
I tried the below way but it doesn't work for me
print test.insert(1, "secondvalue")
Is there any alternate way to do this?
The insert function does not return a value, but rather modifies the array used on it. Here's an example:
test = ['firstvalue', 'thirdvalue']
test.insert(1, "secondvalue")
print test
import collections
header_dict = {'account number':'ACCOUNT_name','accountID':'ACCOUNT_name','name':'client','first name':'client','tax id':'tin'}
#header_dict = collections.defaultdict(lambda: 'tin') # attempted use of defaultdict...destroys my dictionary
given_header = ['account number','name','tax id']#,'tax identification number']#,'social security number'
#given_header = ['account number','name','tax identification number']...non working header layout
fileLayout = [header_dict[ting] for ting in given_header if ting] #create if else..if ting exists, add to list...else if not in list, add to dictionary
def getLayout(ting):
global given_header
global fileLayout
return given_header[fileLayout.index(ting)]
print getLayout('ACCOUNT_name')
print getLayout('client')
print getLayout('tin')
rows = zip((getLayout('ACCOUNT_name'),getLayout('client'),getLayout('tin')))
print rows
I am working with many files of random, mixed up layouts/column orders. I have a set template for my db table of 'ACCOUNT_name','client','tin' that I want the files to be ordered in. I have created a dictionary of the possible header/column names I might find in other files as keys and my set header names as values. So, for example, if I wanted to see where to put the column 'account number' from one of my given files, I would type header_dict['account number'].
This would give me the corresponding column from my template, 'ACCOUNT_name'. This works great...I also added another feature. Instead of having to type 'account number'..I made a list comprehension that looks up each value by key.
This list I just created with the 'fileLayout' list comprehension essentially transforms my given file's header into my desired names: ['ACCOUNT_name','client']
That makes life a lot easier...I know that I want to look up 'ACCOUNT_name', or 'client'. Next I run a function 'getLayout' that returns the index of the desired columns I am searching...So if I want to see where my desired column 'ACCOUNT_name' is in the file, I just run the function which is called like this...
getLayout('ACCOUNT_name')
Now at this point, I can easily print the columns to my order...with:
rows = zip((getLayout('ACCOUNT_name'),getLayout('client'),getLayout('tin')))
print rows
The above code gives me [('account number'),('name'),('tax id')], which is exactly what I want...
But what if there is a new header I am not used to ?? Lets use the same example code above but change the list 'given_header' to this:
given_header = ['account number','name','tax identification number']
I most certainly get the key error, KeyError: 'tax identification number' I know I can use defaultdict but when I try to use it with the set value 'tin', I end up overwriting my entire dictionary... What I would ultimately like to end up doing is this...
I would like to create an else within my list comprehension that allows me to standard input dictionary entries if they don't exist. In other words, since 'tax identification number' does not exists as a key, add it as one to my dict and give it the value 'tin' via raw_input. Has anyone ever done or tried anything like this? Any ideas? If you have and have any suggestions, I am all ears. I'm struggling on this issue...
The way I would want to go about this is in the list comprehension..
fileLayout = [header_dict[ting] for ting in given_header if ting else raw_input('add missing key value pair to dictionary')] # or do something of the sort.
I've used the map function on a dataframe column of postcodes to create a new Series of tuples which I can then manipulate into a new dataframe.
def scrape_data(series_data):
#A bit of code to create the URL goes here
r = requests.get(url)
root_content = r.content
root = lxml.html.fromstring(root_content)
address = root.cssselect(".lr_results ul")
for place in address:
address_property = place.cssselect("li a")[0].text
house_type = place.cssselect("li")[1].text
house_sell_price = place.cssselect("li")[2].text
house_sell_date = place.cssselect("li")[3].text
return address_property, house_type, house_sell_price, house_sell_date
df = postcode_subset['Postcode'].map(scrape_data)
While it works where there is only one property on a results page, it fails to create a tuple for multiple properties.
What I'd like to be able to do is iterate through a series of pages and then add that content to a dataframe. I know that Pandas can convert nested dicts into dataframes, but really struggling to make it work. I've tried to use the answers at How to make a nested dictionary and dynamically append data but I'm getting lost.
At the moment your function only returns for the first place in address (usually in python you would yield (rather than return) to retrieve all the results as a generator.
When subsequently doing an apply/map, you'll usually want the function to return a Series...
However, I think you just want to return the following DataFrame:
return pd.DataFrame([{'address_ property': place.cssselect("li a")[0].text,
'house_type': place.cssselect("li")[1].text,
'house_sell_price': place.cssselect("li")[2].text,
'house_sell_date': place.cssselect("li")[3].text}
for place in address],
index=address)
To make the code work, I eventually reworked Andy Hayden's solution to:
listed = []
for place in address:
results = [{'postcode':postcode_bit,'address_ property': place.cssselect("li a")[0].text,
'house_type': place.cssselect("li")[1].text,
'house_sell_price': place.cssselect("li")[2].text,
'house_sell_date': place.cssselect("li")[3].text}]
listed.extend(results)
return listed
At least I understand a bit more about how Python data structures work now.