neulab/docprompting-conala huggingface dataset:
# BeautifulSoup find tag 'div' with styling 'width=300px;' in HTML string `soup`
soup.findAll('div', style='width=300px;')
# send a signal `signal.SIGUSR1` to the current process
os.kill(os.getpid(), signal.SIGUSR1)
# check if all elements in list `myList` are identical
all(x == myList[0] for x in myList)
# format number of spaces between strings `Python`, `:` and `Very Good` to be `20`
print('%*s : %*s' % (20, 'Python', 20, 'Very Good'))
# How to convert a string from CP-1251 to UTF-8?
d.decode('cp1251').encode('utf8')
# get rid of None values in dictionary `kwargs`
res = {k: v for k, v in list(kwargs.items()) if v is not None}
# get rid of None values in dictionary `kwargs`
res = dict((k, v) for k, v in kwargs.items() if v is not None)
# concatenate a list of strings `['a', 'b', 'c']`
"""""".join(['a', 'b', 'c'])
# sending http headers to `client`
client.send('HTTP/1.0 200 OK\r\n')
# split a multi-line string `inputString` into separate strings
inputString.split('\n')
# Split a multi-line string ` a \n b \r\n c ` by new line character `\n`
' a \n b \r\n c '.split('\n')
# concatenate elements of list `b` by a colon ":"
""":""".join(str(x) for x in b)
# Calculate sum over all rows of 2D numpy array
a.sum(axis=1)
# concatenate items of list `l` with a space ' '
print(' '.join(map(str, l)))
# run script 'hello.py' with argument 'htmlfilename.htm' on terminal using python executable
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')
# convert a string `my_string` with dot and comma into a float number `my_float`
my_float = float(my_string.replace(',', ''))
# convert a string `123,456.908` with dot and comma into a floating number
float('123,456.908'.replace(',', ''))
# set pythonpath in python script.
sys.path.append('/path/to/whatever')
# split string 'Words, words, words.' using a regex '(\\W+)'
re.split('(\\W+)', 'Words, words, words.')
# open a file `Output.txt` in append mode
file = open('Output.txt', 'a')
# argparse add argument with flag '--version' and version action of '%(prog)s 2.0' to parser `parser`
parser.add_argument('--version', action='version', version='%(prog)s 2.0')
# remove key 'c' from dictionary `d`
{i: d[i] for i in d if i != 'c'}
# Create new DataFrame object by merging columns "key" of  dataframes `split_df` and `csv_df` and rename the columns from dataframes `split_df` and `csv_df` with suffix `_left` and `_right` respectively
pd.merge(split_df, csv_df, on=['key'], suffixes=('_left', '_right'))
# Split a string `s` by space with `4` splits
s.split(' ', 4)
# python save list `mylist` to file object 'save.txt'
pickle.dump(mylist, open('save.txt', 'wb'))
# Create 3d array of zeroes of size `(3,3,3)`
numpy.zeros((3, 3, 3))
# cut off the last word of a sentence `content`
""" """.join(content.split(' ')[:-1])
# convert scalar `x` to array
x = np.asarray(x).reshape(1, -1)[(0), :]
# sum all elements of nested list `L`
sum(sum(i) if isinstance(i, list) else i for i in L)
# Multiple each value by `2` for all keys in a dictionary `my_dict`
my_dict.update((x, y * 2) for x, y in list(my_dict.items()))
# running bash script 'sleep.sh'
subprocess.call('sleep.sh', shell=True)
# Join elements of list `l` with a comma `,`
""",""".join(l)
# make a comma-separated string from a list `myList`
myList = ','.join(map(str, myList))
# remove substring 'bag,' from a string 'lamp, bag, mirror'
print('lamp, bag, mirror'.replace('bag,', ''))
# Reverse the order of words, delimited by `.`, in string `s`
""".""".join(s.split('.')[::-1])
# convert epoch time represented as milliseconds `s` to string using format '%Y-%m-%d %H:%M:%S.%f'
datetime.datetime.fromtimestamp(s).strftime('%Y-%m-%d %H:%M:%S.%f')
# parse milliseconds epoch time '1236472051807' to format '%Y-%m-%d %H:%M:%S'
time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(1236472051807 / 1000.0))
# sum elements at index `column` of each list in list `data`
print(sum(row[column] for row in data))
# sum columns of a list `array`
[sum(row[i] for row in array) for i in range(len(array[0]))]
# combine list of dictionaries `dicts` with the same keys in each list to a single dictionary
dict((k, [d[k] for d in dicts]) for k in dicts[0])
# Merge a nested dictionary `dicts` into a flat dictionary by concatenating nested values with the same key `k`
{k: [d[k] for d in dicts] for k in dicts[0]}
# Insert directory 'apps' into directory `__file__`
sys.path.insert(1, os.path.join(os.path.dirname(__file__), 'apps'))
# modify sys.path for python module `subdir`
sys.path.append(os.path.join(os.path.dirname(__file__), 'subdir'))
# Insert a 'None' value into a SQLite3 table.
db.execute("INSERT INTO present VALUES('test2', ?, 10)", (None,))
# flatten list `list_of_menuitems`
[image for menuitem in list_of_menuitems for image in menuitem]
# append elements of a set `b` to a list `a`
a.extend(b)
# Append elements of a set to a list in Python
a.extend(list(b))
# upload file using FTP
ftp.storlines('STOR ' + filename, open(filename, 'r'))
# add one to the hidden web element with id 'XYZ' with selenium python script
browser.execute_script("document.getElementById('XYZ').value+='1'")
# create array containing the maximum value of respective elements of array `[2, 3, 4]` and array `[1, 5, 2]`
np.maximum([2, 3, 4], [1, 5, 2])
# print a list `l` and move first 3 elements to the end of the list
print(l[3:] + l[:3])
# loop over files in directory '.'
for fn in os.listdir('.'):
    if os.path.isfile(fn):
        pass
# loop over files in directory `source`
for (root, dirs, filenames) in os.walk(source):
    for f in filenames:
        pass
# Google App Engine execute GQL query 'SELECT * FROM Schedule WHERE station = $1' with parameter `foo.key()`
db.GqlQuery('SELECT * FROM Schedule WHERE station = $1', foo.key())
# filter rows in pandas starting with alphabet 'f' using regular expression.
df.b.str.contains('^f')
# pandas: delete rows in dataframe `df` based on multiple columns values
df.set_index(list('BC')).drop(tuples, errors='ignore').reset_index()
# format the variables `self.goals` and `self.penalties` using string formatting
"""({:d} goals, ${:d})""".format(self.goals, self.penalties)
# format string "({} goals, ${})" with variables `goals` and `penalties`
"""({} goals, ${})""".format(self.goals, self.penalties)
# format string "({0.goals} goals, ${0.penalties})"
"""({0.goals} goals, ${0.penalties})""".format(self)
# convert list of lists `L` to list of integers
[int(''.join(str(d) for d in x)) for x in L]
# combine elements of each list in list `L` into digits of a single integer
[''.join(str(d) for d in x) for x in L]
# convert a list of lists `L` to list of integers
L = [int(''.join([str(y) for y in x])) for x in L]
# write the elements of list `lines` concatenated by special character '\n' to file `myfile`
myfile.write('\n'.join(lines))
# removing an element from a list based on a predicate 'X' or 'N'
[x for x in ['AAT', 'XAC', 'ANT', 'TTA'] if 'X' not in x and 'N' not in x]
# Remove duplicate words from a string `text` using regex
text = re.sub('\\b(\\w+)( \\1\\b)+', '\\1', text)
# search for string that matches regular expression pattern '(?<!Distillr)\\\\AcroTray\\.exe' in string 'C:\\SomeDir\\AcroTray.exe'
re.search('(?<!Distillr)\\\\AcroTray\\.exe', 'C:\\SomeDir\\AcroTray.exe')
# split string 'QH QD JC KD JS' into a list on white spaces
"""QH QD JC KD JS""".split()
# search for occurrences of regex pattern '>.*<' in xml string `line`
print(re.search('>.*<', line).group(0))
# erase all the contents of a file `filename`
open(filename, 'w').close()
# convert a string into datetime using the format '%Y-%m-%d %H:%M:%S.%f'
datetime.datetime.strptime(string_date, '%Y-%m-%d %H:%M:%S.%f')
# find the index of a list with the first element equal to '332' within the list of lists `thelist`
[index for index, item in enumerate(thelist) if item[0] == '332']
# subscript text 'H20' with '2' as subscripted in matplotlib labels for arrays 'x' and 'y'.
plt.plot(x, y, label='H\u2082O')
# subscript text 'H20' with '2' as subscripted in matplotlib labels for arrays 'x' and 'y'.
plt.plot(x, y, label='$H_2O$')
# loop over a list `mylist` if sublists length equals 3
[x for x in mylist if len(x) == 3]
# initialize a list `lst` of 100 objects Object()
lst = [Object() for _ in range(100)]
# create list `lst` containing 100 instances of object `Object`
lst = [Object() for i in range(100)]
# get the content of child tag with`href` attribute whose parent has css `someclass`
self.driver.find_element_by_css_selector('.someclass a').get_attribute('href')
# joining data from dataframe `df1` with data from dataframe `df2` based on matching values of column 'Date_Time' in both dataframes
df1.merge(df2, on='Date_Time')
# use `%s` operator to print variable values `str1` inside a string
'first string is: %s, second one is: %s' % (str1, 'geo.tif')
# Split a string by a delimiter in python
[x.strip() for x in '2.MATCHES $$TEXT$$ STRING'.split('$$TEXT$$')]
# check if directory `directory ` exists and create it if necessary
if (not os.path.exists(directory)):
    os.makedirs(directory)
# check if a directory `path` exists and create it if necessary
try:
    os.makedirs(path)
except OSError:
    if (not os.path.isdir(path)):
        raise
# check if a directory `path` exists and create it if necessary
distutils.dir_util.mkpath(path)
# check if a directory `path` exists and create it if necessary
try:
    os.makedirs(path)
except OSError as exception:
    if (exception.errno != errno.EEXIST):
        raise
# Replace a separate word 'H3' by 'H1' in a string 'text'
re.sub('\\bH3\\b', 'H1', text)
# substitute ASCII letters in string 'aas30dsa20' with empty string ''
re.sub('\\D', '', 'aas30dsa20')
# get digits only from a string `aas30dsa20` using lambda function
"""""".join([x for x in 'aas30dsa20' if x.isdigit()])
# get a dictionary `records` of key-value pairs in PyMongo cursor `cursor`
records = dict((record['_id'], record) for record in cursor)
# Create new matrix object  by concatenating data from matrix A and matrix B
np.concatenate((A, B))
# concat two matrices `A` and `B` in numpy
np.vstack((A, B))
# find the key associated with the largest value in dictionary `x` whilst key is non-zero value
max(k for k, v in x.items() if v != 0)
# get the largest key whose not associated with value of 0 in dictionary `x`
(k for k, v in x.items() if v != 0)
# get the largest key in a dictionary `x` with non-zero value
max(k for k, v in x.items() if v != 0)
# Update datetime field in `MyModel` to be the existing `timestamp` plus 100 years
MyModel.objects.update(timestamp=F('timestamp') + timedelta(days=36524.25))
# merge list `['it']` and list `['was']` and list `['annoying']` into one list
['it'] + ['was'] + ['annoying']
# increment a value with leading zeroes in a number `x`
str(int(x) + 1).zfill(len(x))
# check if a pandas dataframe `df`'s index is sorted
all(df.index[:-1] <= df.index[1:])
# insert data from a string `testfield` to sqlite db `c`
c.execute("INSERT INTO test VALUES (?, 'bar')", (testfield,))
# decode string "\\x89\\n" into a normal string
"""\\x89\\n""".decode('string_escape')
# convert a raw string `raw_string` into a normal string
raw_string.decode('string_escape')
# convert a raw string `raw_byte_string` into a normal string
raw_byte_string.decode('unicode_escape')
# split a string `s` with into all strings of repeated characters
[m.group(0) for m in re.finditer('(\\d)\\1*', s)]
# scatter a plot with x, y position of `np.random.randn(100)` and face color equal to none
plt.scatter(np.random.randn(100), np.random.randn(100), facecolors='none')
# do a scatter plot with empty circles
plt.plot(np.random.randn(100), np.random.randn(100), 'o', mfc='none')
# filter rows containing key word `ball` in column `ids`
df[df['ids'].str.contains('ball')]
# convert index at level 0 into a column in dataframe `df`
df.reset_index(level=0, inplace=True)
# Add indexes in a data frame `df` to a column `index1`
df['index1'] = df.index
# convert pandas index in a dataframe to columns
df.reset_index(level=['tick', 'obs'])
# Get reverse of list items from list 'b' using extended slicing
[x[::-1] for x in b]
# convert list `list_of_ints` into a comma separated string
""",""".join([str(i) for i in list_of_ints])
# Send a post request with raw data `DATA` and basic authentication with `username` and `password`
requests.post(url, data=DATA, headers=HEADERS_DICT, auth=(username, password))
# Iterate ove list `[1, 2, 3]` using list comprehension
print([item for item in [1, 2, 3]])
# extract all the values with keys 'x' and 'y' from a list of dictionaries `d` to list of tuples
[(x['x'], x['y']) for x in d]
# get the filename without the extension from file 'hemanth.txt'
print(os.path.splitext(os.path.basename('hemanth.txt'))[0])
# create a dictionary by adding each two adjacent elements in tuple `x` as key/value pair to it
dict(x[i:i + 2] for i in range(0, len(x), 2))
# create a list containing flattened list `[['A', 'B', 'C'], ['D', 'E', 'F'], ['G', 'H', 'I']]`
values = sum([['A', 'B', 'C'], ['D', 'E', 'F'], ['G', 'H', 'I']], [])
# select rows in a dataframe `df` column 'closing_price' between two values 99 and 101
df = df[(df['closing_price'] >= 99) & (df['closing_price'] <= 101)]
# replace all occurences of newlines `\n` with `<br>` in dataframe `df`
df.replace({'\n': '<br>'}, regex=True)
# replace all occurrences of a string `\n` by string `<br>` in a pandas data frame `df`
df.replace({'\n': '<br>'}, regex=True)
# create a list containing each two adjacent letters in string `word` as its elements
[(x + y) for x, y in zip(word, word[1:])]
# Get a list of pairs from a string `word` using lambda function
list(map(lambda x, y: x + y, word[:-1], word[1:]))
# extract a url from a string `myString`
print(re.findall('(https?://[^\\s]+)', myString))
# extract a url from a string `myString`
print(re.search('(?P<url>https?://[^\\s]+)', myString).group('url'))
# remove all special characters, punctuation and spaces from a string `mystring` using regex
re.sub('[^A-Za-z0-9]+', '', mystring)
# create a DatetimeIndex containing 13 periods of the second friday of each month starting from date '2016-01-01'
pd.date_range('2016-01-01', freq='WOM-2FRI', periods=13)
# Create multidimensional array `matrix` with 3 rows and 2 columns in python
matrix = [[a, b], [c, d], [e, f]]
# get an absolute file path of file 'mydir/myfile.txt'
os.path.abspath('mydir/myfile.txt')
# split string `my_string` on white spaces
""" """.join(my_string.split())
# get filename without extension from file `filename`
os.path.splitext(filename)[0]
# get a list containing the sum of each element `i` in list `l` plus the previous elements
[sum(l[:i]) for i, _ in enumerate(l)]
# split a string `Docs/src/Scripts/temp` by `/` keeping `/` in the result
"""Docs/src/Scripts/temp""".replace('/', '/\x00/').split('\x00')
# copy all values in a column 'B' to a new column 'D' in a pandas data frame 'df'
df['D'] = df['B']
# find a value within nested json 'data' where the key inside another key 'B' is unknown.
list(data['A']['B'].values())[0]['maindata'][0]['Info']
# check characters of string `string` are true predication of function `predicate`
all(predicate(x) for x in string)
# convert string `user_input` into a list of integers `user_list`
user_list = [int(number) for number in user_input.split(',')]
# Get a list of integers by splitting  a string `user` with comma
[int(s) for s in user.split(',')]
# Sorting a Python list by two criteria
sorted(list, key=lambda x: (x[0], -x[1]))
# sort a list of objects `ut`, based on a function `cmpfun` in descending order
ut.sort(key=cmpfun, reverse=True)
# reverse list `ut` based on the `count` attribute of each object
ut.sort(key=lambda x: x.count, reverse=True)
# sort a list of objects `ut` in reverse order by their `count` property
ut.sort(key=lambda x: x.count, reverse=True)
# click a href button 'Send' with selenium
driver.find_element_by_partial_link_text('Send').click()
# click a href button having text `Send InMail` with selenium
driver.findElement(By.linkText('Send InMail')).click()
# click a href button with text 'Send InMail' with selenium
driver.find_element_by_link_text('Send InMail').click()
# cast an int `i` to a string and concat to string 'ME'
'ME' + str(i)
# Sorting data in DataFrame Pandas
df.sort_values(['System_num', 'Dis'])
# sort a list `l` by length of value in tuple
l.sort(key=lambda t: len(t[1]), reverse=True)
# split string `s` by words that ends with 'd'
re.findall('\\b(\\w+)d\\b', s)
# convert elements of each tuple in list `l` into a string  separated by character `@`
""" """.join([('%d@%d' % t) for t in l])
# convert each tuple in list `l` to a string with '@' separating the tuples' elements
""" """.join([('%d@%d' % (t[0], t[1])) for t in l])
# get the html from the current web page of a Selenium driver
driver.execute_script('return document.documentElement.outerHTML;')
# Get all matches with regex pattern `\\d+[xX]` in list of string `teststr`
[i for i in teststr if re.search('\\d+[xX]', i)]
# select values from column 'A' for which corresponding values in column 'B' will be greater than 50, and in column 'C' - equal 900 in dataframe `df`
df['A'][(df['B'] > 50) & (df['C'] == 900)]
# Sort dictionary `o` in ascending order based on its keys and items
sorted(o.items())
# convert items in `T1` to integers
T2 = [map(int, x) for x in T1]
# call a shell script `./test.sh` using subprocess
subprocess.call(['./test.sh'])
# combine lists `l1` and `l2`  by alternating their elements
[val for pair in zip(l1, l2) for val in pair]
# parse tab-delimited CSV file 'text.txt' into a list
lol = list(csv.reader(open('text.txt', 'rb'), delimiter='\t'))
# group a list of dicts `LD` into one dict by key
print(dict(zip(LD[0], zip(*[list(d.values()) for d in LD]))))
# How do I sum the first value in each tuple in a list of tuples in Python?
sum([pair[0] for pair in list_of_pairs])
# convert unicode string u"{'code1':1,'code2':1}" into dictionary
d = ast.literal_eval("{'code1':1,'code2':1}")
# find all words in a string `mystring` that start with the `$` sign
[word for word in mystring.split() if word.startswith('$')]
# remove any url within string `text`
text = re.sub('^https?:\\/\\/.*[\\r\\n]*', '', text, flags=re.MULTILINE)
# running r script '/pathto/MyrScript.r' from python
subprocess.call(['/usr/bin/Rscript', '--vanilla', '/pathto/MyrScript.r'])
# run r script '/usr/bin/Rscript --vanilla /pathto/MyrScript.r'
subprocess.call('/usr/bin/Rscript --vanilla /pathto/MyrScript.r', shell=True)
# replacing nan in the dataframe `df` with row average
df.fillna(df.mean(axis=1), axis=1)
# Convert unix timestamp '1347517370' to formatted string '%Y-%m-%d %H:%M:%S'
time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(1347517370))
# Call a base class's class method `do` from derived class `Derived`
super(Derived, cls).do(a)
# separate words delimited by one or more spaces into a list
re.split(' +', 'hello world sample text')
# length of longest element in list `words`
len(max(words, key=len))
# get the value associated with unicode key 'from_user' of first dictionary in list `result`
result[0]['from_user']
# Retrieve each line from a file 'File.txt' as a list
[line.split() for line in open('File.txt')]
# swap keys with values in a dictionary `a`
res = dict((v, k) for k, v in a.items())
# Open a file `path/to/FILE_NAME.ext` in write mode
new_file = open('path/to/FILE_NAME.ext', 'w')
# How to count distinct values in a column of a pandas group by object?
df.groupby(['col1', 'col2'])['col3'].nunique().reset_index()
# Check if any key in the dictionary `dict1` starts with the string `EMP$$`
any(key.startswith('EMP$$') for key in dict1)
# create list of values from dictionary `dict1` that have a key that starts with 'EMP$$'
[value for key, value in list(dict1.items()) if key.startswith('EMP$$')]
# print elements of list `list` seperated by tabs `\t`
print('\t'.join(map(str, list)))
# print unicode string '\xd0\xbf\xd1\x80\xd0\xb8' with utf-8
print('\xd0\xbf\xd1\x80\xd0\xb8'.encode('raw_unicode_escape'))
# Encode a latin character in string `Sopet\xc3\xb3n` properly
'Sopet\xc3\xb3n'.encode('latin-1').decode('utf-8')
# regex, find "n"s only in the middle of string `s`
re.findall('n(?<=[^n]n)n+(?=[^n])(?i)', s)
# display the float `1/3*100` as a percentage
print('{0:.0f}%'.format(1.0 / 3 * 100))
# sort a list of dictionary `mylist` by the key `title`
mylist.sort(key=lambda x: x['title'])
# sort a list `l` of dicts by dict value 'title'
l.sort(key=lambda x: x['title'])
# sort a list of dictionaries by the value of keys 'title', 'title_url', 'id' in ascending order.
l.sort(key=lambda x: (x['title'], x['title_url'], x['id']))
# write records in dataframe `df` to table 'test' in schema 'a_schema'
df.to_sql('test', engine, schema='a_schema')
# Extract brackets from string `s`
brackets = re.sub('[^(){}[\\]]', '', s)
# remove duplicate elements from list 'L'
list(dict((x[0], x) for x in L).values())
# read a file `file` without newlines
[line.rstrip('\n') for line in file]
# get the position of item 1 in `testlist`
[i for (i, x) in enumerate(testlist) if (x == 1)]
# get the position of item 1 in `testlist`
for i in [i for (i, x) in enumerate(testlist) if (x == 1)]:
    pass
# get the position of item 1 in `testlist`
for i in (i for (i, x) in enumerate(testlist) if (x == 1)):
    pass
# get the position of item 1 in `testlist`
gen = (i for (i, x) in enumerate(testlist) if (x == 1))
for i in gen:
    pass
# get the position of item `element` in list `testlist`
print(testlist.index(element))
# get the position of item `element` in list `testlist`
try:
    print(testlist.index(element))
except ValueError:
    pass
# find the first element of the tuple with the maximum second element in a list of tuples `lis`
max(lis, key=lambda item: item[1])[0]
# get the item at index 0 from the tuple that has maximum value at index 1 in list `lis`
max(lis, key=itemgetter(1))[0]
# convert list of tuples `L` to a string
""", """.join('(' + ', '.join(i) + ')' for i in L)
# Django set default value of field `b` equal to '0000000'
b = models.CharField(max_length=7, default='0000000', editable=False)
# convert a list  into a generator object
(n for n in [1, 2, 3, 5])
# remove elements from list `oldlist` that have an index number mentioned in list `removelist`
newlist = [v for i, v in enumerate(oldlist) if i not in removelist]
# Open a file `yourfile.txt` in write mode
f = open('yourfile.txt', 'w')
# convert tuple of tuples `(('aa',), ('bb',), ('cc',))` to tuple
from functools import reduce
reduce(lambda a, b: a + b, (('aa',), ('bb',), ('cc',)))
# convert tuple of tuples `(('aa',), ('bb',), ('cc',))` to list in one line
map(lambda a: a[0], (('aa',), ('bb',), ('cc',)))
# Python Pandas: How to replace a characters in a column of a dataframe?
df['range'].replace(',', '-', inplace=True)
# unzip the list `[('a', 1), ('b', 2), ('c', 3), ('d', 4)]`
zip(*[('a', 1), ('b', 2), ('c', 3), ('d', 4)])
# unzip list `original`
result = ([a for (a, b) in original], [b for (a, b) in original])
# unzip list `original` and return a generator
result = ((a for (a, b) in original), (b for (a, b) in original))
# unzip list `[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', )]`
zip(*[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e',)])
# unzip list `[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', )]` and fill empty results with None
map(None, *[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e',)])
# Add key "mynewkey" to dictionary `d` with value "mynewvalue"
d['mynewkey'] = 'mynewvalue'
# Add key 'a' to dictionary `data` with value 1
data.update({'a': 1, })
# Add key 'a' to dictionary `data` with value 1
data.update(dict(a=1))
# Add key 'a' to dictionary `data` with value 1
data.update(a=1)
# find maximal value in matrix `matrix`
max([max(i) for i in matrix])
# Round number `answer` to 2 precision after the decimal point
answer = str(round(answer, 2))
# extract ip address from an html string
ip = re.findall('[0-9]+(?:\\.[0-9]+){3}', s)
# append each line in file `myfile` into a list
[x for x in myfile.splitlines() if x != '']
# Get a list of integers `lst` from a file `filename.txt`
lst = map(int, open('filename.txt').readlines())
# Python split a string using regex
re.findall('(.+?):(.+?)\\b ?', text)
# generate all 2-element subsets of tuple `(1, 2, 3)`
list(itertools.combinations((1, 2, 3), 2))