text
stringlengths
4
1.08k
sum of all values in a python dict `d`,sum(d.values())
convert python dictionary `your_data` to json array,"json.dumps(your_data, ensure_ascii=False)"
assign an array of floats in range from 0 to 100 to a variable `values`,"values = np.array([i for i in range(100)], dtype=np.float64)"
sort a list of dictionaries `list_of_dct` by values in an order `order`,"sorted(list_of_dct, key=lambda x: order.index(list(x.values())[0]))"
change the case of the first letter in string `s`,return s[0].upper() + s[1:]
"join list of numbers `[1,2,3,4] ` to string of numbers.",""""""""""""".join([1, 2, 3, 4])"
delete every non `utf-8` characters from a string `line`,"line = line.decode('utf-8', 'ignore').encode('utf-8')"
execute a command `command ` in the terminal from a python script,os.system(command)
MySQL execute query 'SELECT * FROM foo WHERE bar = %s AND baz = %s' with parameters `param1` and `param2`,"c.execute('SELECT * FROM foo WHERE bar = %s AND baz = %s', (param1, param2))"
Parse string `datestr` into a datetime object using format pattern '%Y-%m-%d',"dateobj = datetime.datetime.strptime(datestr, '%Y-%m-%d').date()"
How can I send a signal from a python program?,"os.kill(os.getpid(), signal.SIGUSR1)"
Decode Hex String in Python 3,bytes.fromhex('4a4b4c').decode('utf-8')
check if all elements in a list are identical,all(x == myList[0] for x in myList)
Format string dynamically,"print('%*s : %*s' % (20, 'Python', 20, 'Very Good'))"
How to convert a string from CP-1251 to UTF-8?,d.decode('cp1251').encode('utf8')
How I can get rid of None values in dictionary?,"res = {k: v for k, v in list(kwargs.items()) if v is not None}"
How I can get rid of None values in dictionary?,"res = dict((k, v) for k, v in kwargs.items() if v is not None)"
Python: how to get the final output of multiple system commands?,"subprocess.check_output('ps -ef | grep something | wc -l', shell=True)"
splitting and concatenating a string,""""""""""""".join(['a', 'b', 'c'])"
Finding the intersection between two series in Pandas,pd.Series(list(set(s1).intersection(set(s2))))
Sending http headers with python,client.send('HTTP/1.0 200 OK\r\n')
Python -Remove Time from Datetime String,"then = datetime.datetime.strptime(when, '%Y-%m-%d').date()"
How do I split a multi-line string into multiple lines?,inputString.split('\n')
How do I split a multi-line string into multiple lines?,' a \n b \r\n c '.split('\n')
How to join mixed list (array) (with integers in it) in Python?,""""""":"""""".join(str(x) for x in b)"
Fastest way to get the first object from a queryset in django?,Entry.objects.filter()[:1].get()
How to calculate the sum of all columns of a 2D numpy array (efficiently),a.sum(axis=1)
"Python, how to enable all warnings?",warnings.simplefilter('always')
Python printing without commas,"print(' '.join(map(str, l)))"
OSError: [WinError 193] %1 is not a valid Win32 application,"subprocess.call(['python.exe', 'hello.py', 'htmlfilename.htm'])"
How can I parse a time string containing milliseconds in it with python?,"time.strptime('30/03/09 16:31:32.123', '%d/%m/%y %H:%M:%S.%f')"
How can I convert a string with dot and comma into a float number in Python,"my_float = float(my_string.replace(',', ''))"
How can I convert a string with dot and comma into a float number in Python,"float('123,456.908'.replace(',', ''))"
"In Python script, how do I set PYTHONPATH?",sys.path.append('/path/to/whatever')
Determining the unmatched portion of a string using a regex in Python,"re.split('(\\W+)', 'Words, words, words.')"
How to read data from Excel and write it to text file line by line?,"file = open('Output.txt', 'a')"
download a file over HTTP,"urllib.request.urlretrieve('http://www.example.com/songs/mp3.mp3', 'mp3.mp3')"
download a file over HTTP,u = urllib.request.urlopen(url)
download a file over HTTP,"response = urllib.request.urlopen('http://www.example.com/')
html = response.read()"
download a file over HTTP,r = requests.get(url)
download a file over HTTP,"response = requests.get(url, stream=True)"
Python's argparse to show program's version with prog and version string formatting,"parser.add_argument('--version', action='version', version='%(prog)s 2.0')"
Remove key from dictionary in Python returning new dictionary,{i: d[i] for i in d if i != 'c'}
Merging two pandas dataframes,"pd.merge(split_df, csv_df, on=['key'], suffixes=('_left', '_right'))"
Python regular expression split() string,"s.split(' ', 4)"
How to read keyboard-input?,input('Enter your input:')
Auto reloading python Flask app upon code changes,app.run(debug=True)
Python save list and read data from file,"pickle.dump(mylist, open('save.txt', 'wb'))"
Numpy: Multiplying a matrix with a 3d tensor -- Suggestion,"scipy.tensordot(P, T, axes=[1, 1]).swapaxes(0, 1)"
How to create nested lists in python?,"numpy.zeros((3, 3, 3))"
Python: Cut off the last word of a sentence?,""""""" """""".join(content.split(' ')[:-1])"
Numpy convert scalars to arrays,"x = np.asarray(x).reshape(1, -1)[(0), :]"
Finding the sum of a nested list of ints,"sum(sum(i) if isinstance(i, list) else i for i in L)"
Convert hex to float,"struct.unpack('!f', '470FC614'.decode('hex'))[0]"
Python: Perform an operation on each dictionary value,"my_dict.update((x, y * 2) for x, y in list(my_dict.items()))"
Running bash script from within python,"subprocess.call('sleep.sh', shell=True)"
How would you make a comma-separated string from a list?,""""""","""""".join(l)"
How would you make a comma-separated string from a list?,"myList = ','.join(map(str, myList))"
Print a list in reverse order with range()?,list(reversed(list(range(10))))
How can i subtract two strings in python?,"print('lamp, bag, mirror'.replace('bag,', ''))"
python reverse tokens in a string,"""""""."""""".join(s.split('.')[::-1])"
converting epoch time with milliseconds to datetime,datetime.datetime.fromtimestamp(s).strftime('%Y-%m-%d %H:%M:%S.%f')
converting epoch time with milliseconds to datetime,"time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(1236472051807 / 1000.0))"
Getting the date of 7 days ago from current date in python,(datetime.datetime.now() - datetime.timedelta(days=7)).date()
How can I sum a column of a list?,print(sum(row[column] for row in data))
How can I sum a column of a list?,[sum(row[i] for row in array) for i in range(len(array[0]))]
How to encode text to base64 in python,"base64.b64encode(bytes('your string', 'utf-8'))"
How can I combine dictionaries with the same keys in python?,"dict((k, [d[k] for d in dicts]) for k in dicts[0])"
How can I combine dictionaries with the same keys in python?,{k: [d[k] for d in dicts] for k in dicts[0]}
How do I get the url parameter in a Flask view,request.args['myParam']
Identify duplicate values in a list in Python,"[k for k, v in list(Counter(mylist).items()) if v > 1]"
How do you modify sys.path in Google App Engine (Python)?,"sys.path.insert(1, os.path.join(os.path.dirname(__file__), 'apps'))"
How do you modify sys.path in Google App Engine (Python)?,"sys.path.append(os.path.join(os.path.dirname(__file__), 'subdir'))"
Insert Null into SQLite3 in Python,"db.execute(""INSERT INTO present VALUES('test2', ?, 10)"", (None,))"
Flattening a shallow list in Python,[image for menuitem in list_of_menuitems for image in menuitem]
Append elements of a set to a list in Python,a.extend(b)
Append elements of a set to a list in Python,a.extend(list(b))
"Python, Pandas : write content of DataFrame into text File","np.savetxt('c:\\data\\np.txt', df.values, fmt='%d')"
"Python, Pandas : write content of DataFrame into text File","df.to_csv('c:\\data\\pandas.txt', header=None, index=None, sep=' ', mode='a')"
how to get the last part of a string before a certain character?,print(x.rpartition('-')[0])
how to get the last part of a string before a certain character?,"print(x.rsplit('-', 1)[0])"
FTP upload files Python,"ftp.storlines('STOR ' + filename, open(filename, 'r'))"
Write value to hidden element with selenium python script,"browser.execute_script(""document.getElementById('XYZ').value+='1'"")"
Combining two numpy arrays to form an array with the largest value from each array,"np.maximum([2, 3, 4], [1, 5, 2])"
How to print an entire list while not starting by the first item,print(l[3:] + l[:3])
loop over files,"for fn in os.listdir('.'):
if os.path.isfile(fn):
pass"
loop over files,"for (root, dirs, filenames) in os.walk(source):
for f in filenames:
pass"
Create random list of integers in Python,[int(1000 * random.random()) for i in range(10000)]
Using %f with strftime() in Python to get microseconds,datetime.datetime.now().strftime('%H:%M:%S.%f')
Build a GQL query (for Google App Engine) that has a condition on ReferenceProperty,"db.GqlQuery('SELECT * FROM Schedule WHERE station = $1', foo.key())"
How to filter rows in pandas by regex,df.b.str.contains('^f')
What is the best way to print a table with delimiters in Python,print('\n'.join('\t'.join(str(col) for col in row) for row in tab))
Pandas: Delete rows based on multiple columns values,"df.set_index(list('BC')).drop(tuples, errors='ignore').reset_index()"
String Formatting in Python 3,"""""""({:d} goals, ${:d})"""""".format(self.goals, self.penalties)"
String Formatting in Python 3,"""""""({} goals, ${})"""""".format(self.goals, self.penalties)"