content stringlengths 42 6.51k |
|---|
def anagram(word):
"""Returns random words from a file
Parameters
----------
word : str
Word in which we will return all permutations of
Raises
------
TypeError
If no no or 1 parameter was given...requires two keyword parameters path and amm... |
def fragment_positions(fragment):
"""Get the fragmnent position."""
return (
len(fragment),
[aln.chromosome for aln in fragment],
[aln.position for aln in fragment],
[aln.flag for aln in fragment]) |
def guard(f, *args, **kwargs):
"""
Run a function.
Return (is_error, result), where ``is_error`` is a boolean indicating whether
it raised an exception. In that case, ``result`` will be an exception.
"""
try:
return (False, f(*args, **kwargs))
except Exception as e:
return (... |
def egcd(a, b):
"""
Given a, and b, calculates the egcd and returns the x and y values
>>> egcd(9, 6)
(1, -1)
>>> egcd(51, 0)
(1, 0)
>>> egcd(1,0)
(1, 0)
"""
if b == 0:
return (1, 0)
else:
q = a // b
r = a % b
(s, t) = egcd(b, r)
return... |
def _get_fields(attrs, field_class, pop=False):
"""
Get fields from a class.
:param attrs: Mapping of class attributes
:param type field_class: Base field class
:param bool pop: Remove matching fields
"""
fields = [
(field_name, field_value)
for field_name, field_value in at... |
def make_geotransform(x_len, y_len, origin):
"""
Build an array of affine transformation coefficients.
Parameters:
x_len (int or float): The length of a pixel along the x axis.
Generally, this will be a positive value.
y_len (int of float): The length of a pixel along the y axi... |
def divide_by(value, arg):
"""
Returns the result of the division of value with arg.
"""
result = 0
try:
result = value / arg
except:
# error in division
pass
return result |
def selectionSort(array: list = [10, 9, 8, 7 ,6 , 5 ,4 ,3, 2, 1], wasChange: bool = False) -> list:
"""This method will sort a number array.
Args:
array (list, optional): unordered number array. Defaults to [10, 9, 8, 7, 6, 5, 4, 3, 2, 1].
wasChange (bool, optional): This conditional is to indicate tha... |
def _makequalifiers(qualifiers, indent):
"""Return a MOF fragment for a NocaseDict of qualifiers."""
if len(qualifiers) == 0:
return ''
return '[%s]' % ',\n '.ljust(indent + 2). \
join([q.tomof(indent) for q in sorted(qualifiers.values())]) |
def rectintersection(r1, r2):
"""Returns the rect corresponding to the intersection between two rects.
Returns `None` if non-overlapping.
"""
if r1[0] > r2[2] or r1[2] < r2[0] or r1[1] > r2[3] or r1[3] < r2[1]: return None
ret = [max(r1[0], r2[0]), max(r1[1], r2[1]), min(r1[2], r2[2]), min(r1[3], r2... |
def gettype(var):
"""Return the type of var
Parameters:
----------
var: any type
Type to be tested
Returns:
-------
type: type
Type of var
Examples:
--------
>>> gettype(3)
<type 'int'>
>>> gettype(None)
<type 'int'>
>>> gettype([1,2,3])
<ty... |
def naics_filter(opps):
"""Filter out opps without desired naics
Arguments:
opps {list} -- a list of sam opportunity api results
naics {list} -- a list of naics to filter with
Returns:
[list] -- a subset of results with matching naics
"""
naics = ('334111', '334118'... |
def _capped_double_heads(num_heads, cap=16):
"""Calculate the number of heads for the attention layers with more heads.
The number of heads will be twice the normal amount (num_heads), until it
reaches |cap| heads.
Args:
num_heads: the num_heads hparam for the model.
cap: the maximum number of heads |... |
def from_time_str(time_str):
"""Parses the number of seconds from the given time string in
[[HH:]MM:]SS[.XXX] format.
Examples::
"00.0" => 0.0
"01:00.0" => 60.0
"01:05.0" => 65.0
"16700:52:03.0" => 60123123.0
Args:
time_str: a time ... |
def _run_arrays(inner_fn, slice, arrays_dict, **kwargs):
"""
Assumes that the lengths of the value arrays are all the same.
"""
# SETUP the re-usable kwargs with parameters and arrays and then poke values one row at a time
res = []
for row_i in range(slice[0], slice[1]):
for field_i, (ke... |
def get_shell(orb):
"""Get the angular quantum numbers for a GTO
according to its respective shell"""
if "s" in orb:
return (0, 0, 0)
if "px" in orb:
return (1, 0, 0)
if "py" in orb:
return (0, 1, 0)
if "pz" in orb:
return (0, 0, 1)
return None |
def listify(item):
""" Ensure that the input is a list or tuple.
Parameters
----------
item: object or list or tuple
the input data.
Returns
-------
out: list
the liftify input data.
"""
if isinstance(item, list) or isinstance(item, tuple):
return item
e... |
def roc(counts):
"""Function computing TPR and FPR.
Output arguments:
=================
tpr : float
True positive rate
fpr : float
False positive rate
"""
tp, fp, tn, fn = counts
return float(tp) / (tp+fn), float(fp) / (fp+tn) |
def derivative2_centered_h1(target, y):
"""
Implements the taylor centered approach to calculate the second derivative.
:param target: the position to be derived, must be len(y)-1 > target > 0
:param y: an array with the values
:return: the centered second derivative of target
"""
if len(y... |
def compass_angle(data: list, angles: tuple = (0.0, 360.0)) -> list:
"""
Filter out images that do not lie within compass angle range
:param data: The data to be filtered
:type data: list
:param angles: The compass angle range to filter through
:type angle: tuple of floats
:return: A feat... |
def _or_optional_event(env, event, optional_event):
"""If the optional_event is None, the event is returned. Otherwise the event and optional_event are combined
through an any_of event, thus returning an event that will trigger if either of these events triggers.
Used by single_run_process to combine an eve... |
def gcd(m, n):
"""
Euclid's Algorithm
"""
while m % n != 0:
oldm = m
oldn = n
m = oldn
n = oldm % oldn
return n |
def is_shutdown_test(item):
"""Return `True` if the item is a launch test."""
return getattr(item, '_launch_pytest_is_shutdown', False) |
def canConstruct_v6(ransomNote: str, magazine: str) -> bool:
"""
This solution, I picked from the problem discussion page.
Contributed by user 'siwal'.
I liked the intuitive and straight forward approach:
1) Take the next letter from the note.
2) If the required record is not found in a ... |
def _lc_list(lst):
"""
Return a lower-cased list from the input list.
"""
result = []
for value in lst:
result.append(value.lower())
return result |
def group_iam_policies_by_targets(policies):
""" Groups the collection of IAM actions by target. """
policies_by_targets = {}
for policy in policies:
target = policy['properties']['resource']
if not target in policies_by_targets:
policies_by_targets[target] = []
policies... |
def isurl(url: str) -> bool:
"""Check *url* is URL or not."""
if url and '://' in url:
return True
else:
return False |
def getBPDifferenceDistance(stack1, stack2):
"""
Based on the not identical amount of base pairs within both structure stacks
"""
d = 0
for i in stack1.keys():
# check base pairs in stack 1
if i < stack1[i] and stack1[i] != stack2[i]:
d += 1
# check base pairs in ... |
def get_template_from_path(path: str) -> str:
"""Convert a normal path back to its template representation."""
# replace all path parts with the template tags
path = path.replace("\\", "/")
return path |
def get_riming_class_name_dict(method='Praz2017'):
"""
Get riming class ID from riming name
according to a given hydrometeor classif method
Input:
method: hydro class method. Default Praz2017 based on
https://amt.copernicus.org/articles/10/1335/2017/
"""
if method == 'Praz2017... |
def attrsearch(o, attr_substr):
"""
Return a list of any attributes of object o that have the string
attr_substr in the name of the attribute.
>>> attrsearch(dict(), 'key')
['fromkeys', 'has_key', 'iterkeys', 'keys', 'viewkeys']
>>> attrsearch(object(), 'vermicious knid')
[]
"""
... |
def IonSeriesUsed(IonSeries):
"""
01 - A series
02 - placeholder (was A - NH3 series in older versions of Mascot)
03 - A++ series
04 - B series
05 - placeholder (was B - NH3 series in older versions of Mascot)
06 - B++ series
07 - Y series
08 - placeholder (was Y - NH3 series in olde... |
def jsonKeys2str(x):
"""Some of the yamls have integer keys, which json converts to string.
in the future if there are keys that are strings that are intended to be left
as strings this may break"""
if isinstance(x, dict):
return {(int(k) if k.isdigit() else k):v for k, v in x.items()}
retur... |
def lowest_cost_action(ic, dc, sc, im, dm, sm, cost):
"""Given the following values, choose the action (insertion, deletion,
or substitution), that results in the lowest cost (ties are broken using
the 'match' score). This is used within the dynamic programming algorithm.
* ic - insertion cost
* dc... |
def trace_overall_index(batch_idx, test_time_indices):
"""
Given
batch_idx: the particular program this all corresponds to
test_time_indices: list of which (tests, timestep) to select
Returns (trace_idxs, time_idxs)
trace_idxs: the indices int the traces to be returned
time_... |
def itemmap(func, d, factory=dict):
""" Apply function to items of dictionary
>>> accountids = {"Alice": 10, "Bob": 20}
>>> itemmap(reversed, accountids) # doctest: +SKIP
{10: "Alice", 20: "Bob"}
See Also:
keymap
valmap
"""
rv = factory()
rv.update(map(func, d.items())... |
def get_grades(n_students):
"""Prompt the user to input the grades for n students.
Args:
n_students: int. Number of grades to input.
Returns: a list of floating point values
"""
grade_list = []
# Get the inputs from the user
for _ in range(n_students):
grade_list.append(int... |
def ambientT(y, T0 = 20):
"""
y - in mmm
output in degC
"""
return T0 + y * (3/100) |
def unionranges(rangeslist):
"""Return the union of some closed intervals
>>> unionranges([])
[]
>>> unionranges([(1, 100)])
[(1, 100)]
>>> unionranges([(1, 100), (1, 100)])
[(1, 100)]
>>> unionranges([(1, 100), (2, 100)])
[(1, 100)]
>>> unionranges([(1, 99), (1, 100)])
[(1,... |
def is_link(test_string):
"""check if the string is a web link
Args:
test_string (str): input string
Returns:
bool: if string is an http link
"""
return test_string.startswith('http') |
def increment_list_by_index(list_to_increment, index_to_increment, increment_value):
"""
very simple but general method to increment the odes by a specified value
:param list_to_increment: list
the list to be incremented, expected to be the list of ODEs
:param index_to_increment: int
th... |
def make_divisible(
value: int or float,
divisor: int = 8,
round_bias: float = 0.9):
"""
__version__ = 1.0
__date__ = Mar 7, 2022
"""
round_value = max(divisor, int(value + divisor / 2) // divisor * divisor)
assert 0 < round_bias < 1
if round_value < round_bias * va... |
def tp_rate(TP, pos):
"""
Gets true positive rate.
:param TP: Number of true positives
:type TP: `int`
:param pos: Number of positive labels
:type pos: `int`
:return: true positive rate
:rtype: `float`
"""
if pos == 0:
return 0
else:
return TP / pos |
def xor_text(text, xor_key, **kwargs):
"""
# uses xor to encrypt/decrypt some text given a xor_key
>>> text = "Hello, World!"
>>> xor_key = "secret"
>>> encrypted = xor_text(text, xor_key)
>>> encrypted
';\x00\x0f\x1e\nXS2\x0c\x00\t\x10R'
>>> decrypted = xor_text(encrypted, xor_key)
... |
def _is_close(d1, d2, atolerance=0, rtolerance=0):
"""Determines whether two adjacency matrices are within
a provided tolerance.
Parameters
----------
d1 : dict
Adjacency dictionary
d2 : dict
Adjacency dictionary
atolerance : float
Some scalar tolerance... |
def avg(tup):
"""
Returns average of all of the elements in the tuple.
Remember that the average of a tuple is the sum of all of the elements in the
tuple divided by the number of elements in the tuple.
Examples:
avg((1.0, 2.0, 3.0)) returns 2.0
avg((1.0, 1.0, 3.0, 5.0)) returns 2.... |
def get_result(response):
"""
Get the desired result from an API response.
:param response: Requests API response object
"""
try:
payload = response.json()
except AttributeError:
payload = response
if 'results' in payload:
return payload['results']
# Or just re... |
def seq_join(seq, val):
"""
Flatten input sequence of lists into a single list. Insert separator
value if not None.
@param[in] seq sequence of lists
@param[in] val separator value, will be put between sub-sequences in the
resulting list if not None.
@returns resulting flattened li... |
def mask_alternatives(alternatives):
"""
:param alternatives: Extra security alternatives collected from user
:type alternatives: dict
:return: Masked extra security alternatives
:rtype: dict
"""
if alternatives:
# Phone numbers
masked_phone_numbers = []
for phone_num... |
def funky_sum(a, b, mix):
"""
Returns a mixture between a and b.
If mix is 0, returns a. If mix is 1, returns b. Otherwise returns a linear
interpolation between them. If mix is outside the range of 0 and 1, it is
capped at those numbers.
"""
if mix < 0:
return a
elif mix > 1:
... |
def _get_next_key(key, length):
"""Returns reverse(reverse(key, len) + 1, len), where reverse(key, len) is the
bit-wise reversal of the length least significant bits of key"""
step = 1 << (length - 1)
while key & step:
step >>= 1
return (key & (step - 1)) + step |
def contains_timezone(format_string: str) -> bool:
"""
Give an strftime style format string, check if it contains a %Z or %z timezone
format directive.
:param format_string: The format string to check.
:return: True if it does contain a timezone directive. False otherwise.
"""
is_format_cha... |
def any2utf8(text, errors='strict', encoding='utf8'):
"""Convert a unicode or bytes string in the given encoding into a utf8 bytestring.
Parameters
----------
text : str
Input text.
errors : str, optional
Error handling behaviour if `text` is a bytestring.
encoding : str, option... |
def map_into_range(low, high, raw_value):
"""
Map an input function into an output value, clamping such that the magnitude of the output is at most 1.0
:param low:
The value in the input range corresponding to zero.
:param high:
The value in the input range corresponding to 1.0 or -1.0,... |
def twos_complement(val, bits):
"""Retuns the 2-complemented value of val assuming bits word width"""
if (val & (1 << (bits - 1))) != 0: # if sign bit is set
val = val - (2 ** bits) # compute negative value
return val |
def _need_loop(v):
"""
if a variable should loop to concat string
:param v: any variable
:return: Boolean
"""
return isinstance(v, list) or isinstance(v, dict) or isinstance(v, tuple) |
def adder(x, y):
"""Adds two numbers together.
>>> adder(1, 1)
2
>>> adder(-1, 1)
0
"""
return x + y + 1 |
def embed_root(html_string: str) -> str:
"""
Embed the root of the workspace in the html string.
"""
root_string = "`http://${window.HOST}:${window.PORT}`"
replace_string = "''"
html_string = html_string.replace(root_string, replace_string)
wssr_string = "`ws://${window.HOST}:${window.P... |
def reverse(text: str) -> str:
"""Return the reverse of a given string."""
return text[::-1] |
def strip_api(server_url):
"""
Strips "api/" from the end of ``server_url``, if present
>>> strip_api('https://play.dhis2.org/demo/api/')
'https://play.dhis2.org/demo/'
"""
if server_url.rstrip('/').endswith('api'):
i = len(server_url.rstrip('/')) - 3
return server_url[:i]
... |
def parse_connection(connection_string):
"""Parse a connection string.
The connection string must be of the form
proto:address:port,proto:address:port,...
The parsing logic here must be identical to the one at
https://github.com/openvswitch/ovs/blob/master/python/ovs/db/idl.py#L162
for remote ... |
def add(a, b):
"""
Adds stuff
"""
return a + b; |
def clean(query: str) -> str:
""" cleans strings from new lines and wrapping whitespaces"""
return query.replace('"', '""').replace("\r\n", " ").replace("\n", " ").strip() |
def getColourStats(colourData):
"""getColourStats.
Args:
colourData:
"""
import numpy as n
x = n.array(colourData)[:,0]
y = n.array(colourData)[:,1]
meanColour = y.mean()
# We can rewrite the line equation as y = Ap, where A = [[x 1]]
# and p = [[m], [c]]. Now use lstsq ... |
def filter_records_by_victory(records: list) -> list:
"""Filter out records for a specific character"""
specific_records = []
for record in records:
if record["event"]["victory"]:
specific_records.append(record)
return specific_records |
def collect_specific_bytes(bytes_object, start_position, width, relative_to=0):
"""
Collects specific bytes within a bytes object.
:param bytes_object: an opened bytes object
:param start_position: the position to start to read at
:param width: how far to read from the start position
:param rela... |
def sub_template(template,template_tag,substitution):
"""
make a substitution for a template_tag in a template
"""
template = template.replace(template_tag,substitution)
return template |
def _is_unique_msg(dialect, msg):
"""
easier unit testing this way
"""
if dialect == 'postgresql':
if 'duplicate key value violates unique constraint' in msg:
return True
elif dialect == 'mssql':
if 'Cannot insert duplicate key' in msg:
return True
eli... |
def _guess_variables(polynomial, *args):
"""
Return the polynomial variables
INPUT:
- ``polynomial`` -- a polynomial.
- ``*args`` -- the variables. If none are specified, all variables
in ``polynomial`` are returned. If a list or tuple is passed,
the content is returned. If multiple a... |
def flatten(iterables, start_with=None):
"""Takes a list of lists ``iterables`` and returns a list containing elements of every list.
If ``start_with`` is not ``None``, the result will start with ``start_with`` items, exactly as
if ``start_with`` would be the first item of lists.
"""
result = []
... |
def choosecat(str, classnames):
""" Gets a string and tries to match its category with an int. """
for i, id in enumerate(classnames):
if id in str:
return i
return None |
def irpf(base, porcentaje=12.5,prorrateado=False):
"""
irpf (sueldo,porcentaje, prorrateado=boolean)
"""
if prorrateado:
cantidad_prorateada = base/6
if type(base)==float and type(porcentaje)==float:
return (base/100) * porcentaje
else:
return None |
def float_dist(id1, id2):
"""
Compute distance between two identities for NumPyDB.
Assumption: id1 and id2 are real numbers (but always sent
as strings).
This function is typically used when time values are
used as identifiers.
"""
return abs(float(id1) - float(id2)) |
def triangle_shape(height):
"""Print a pyramid made of "x"
Args:
height (int): The height of the pyramid
Returns:
str: a string representing the pyramid, made with the character "x"
"""
pyramid = ""
if height == 0:
return pyramid
for i in range(height):
pyr... |
def isShiftCharacter(character):
"""Returns True if the key character is uppercase or shifted."""
return character.isupper() or character in '~!@#$%^&*()_+{}|:"<>?' |
def dict_to_tuple(dictionary):
"""
>>> dict_to_tuple({'id':[1,2,3,4],'testing':1,'bla':'three'})
[('testing', 1), ('bla', 'three'), ('id', 1), ('id', 2), ('id', 3), ('id', 4)]
>>>
"""
return_list = []
for key, value in dictionary.items():
if isinstance(value, list):
for... |
def find_outbound_connections(l, node_index, node_value):
"""Returns a list indicating the destination nodes of outbound edges
Helper function for constructing a graph showing which integers in list l
are divisors of integers in l with a larger index.
Args:
l: The list of integers that contain... |
def updateComboGroupLazy(player, comboGroup):
"""Computes the final combo group based on combo state start and end, using
the lazy startegy.
Lazy:
include any combo from start state that remains in end state"""
newComboGroup = []
for combo in comboGroup:
orientation = combo.orientation()
if orientation ==... |
def _create_creds_dict(creds_str):
""" Takes the credentials str and converts it to a dict
Parameters
----------
creds_str : str
credentials string with the below format where the user has inserted their values:
'host=my_hostname dbname=my_dbname user=my_user password=my_password port=1... |
def create_word_weight_dictionary(post):
"""
This function creates a word weight dictionary whose keys are
word names and the values are word weights.
:param post: A dict, the Post dictionary from an HTTP Request
:return: A dict, containing word names and associated word weights
"""
word_dic... |
def converttabs(text, spaces=4):
"""
Convert all the tabs to a specific amount of spaces
:type text: string
:param text: The text to convert tabs to spaces on
:type spaces: integer
:param spaces: The amount of spaces to replace tabs to.
"""
return text.replace('\t', ' ' * spaces) |
def exponential_decay(step, rate, decay_steps, start_step=0):
"""A standard exponential decay, scaling the learning rate by :obj:`rate`
every :obj:`decay_steps` steps.
"""
return rate ** (max(step - start_step + decay_steps, 0) // decay_steps) |
def stats(d_raw_materials, f_total_money_collected):
"""
Show machine statistics
Params:
d_raw_materials: dict
f_money_collected: float
Returns:
str
"""
cm_stats = 'sugar {0} tablespoons remaining\n'.format(d_raw_materials['sugar'])
cm_stats += 'butter {0} teaspoons... |
def gassmann_sat2dry(Ksat, Kmin, Kfl, phi):
"""
Gassman substitution from Saturated moduli to dry rock moduli
"""
a = Ksat*(phi*Kmin/Kfl + 1.0 - phi) - Kmin
b = phi*Kmin/Kfl + Ksat/Kmin - 1.0 - phi
Kdry = a/b
return Kdry |
def contains_dir(hdfs_dirs, sub_folder):
"""
Support for Lambda Function to check if a HDFS subfolder is contained by the HDFS directory
"""
if sub_folder in hdfs_dirs:
return True
else:
# Debug
# print('{}, {}'.format(sub_folder, hdfs_dirs))
pass
return False |
def AUC_calc(item, TPR):
"""
Calculate Area under the ROC/PR curve for each class (AUC/AUPR).
:param item: True negative rate (TNR) or Positive predictive value (PPV)
:type item: float
:param TPR: sensitivity, recall, hit rate, or true positive rate
:type TPR: float
:return: AUC/AUPR as flo... |
def is_job_active(jobststus):
"""
Check if jobstatus is one of the active
:param jobststus: str
:return: True or False
"""
end_status_list = ['finished', 'failed', 'cancelled', 'closed']
if jobststus in end_status_list:
return False
return True |
def insertionSort(data):
""" Implementation of the insertion sort algorithm in ascending order """
for unsortedIndex in range(len(data)):
unsortedData = data[unsortedIndex]
sortedIndex = unsortedIndex
while sortedIndex > 0 and unsortedData < data[sortedIndex-1]:
data[sortedIn... |
def _fix2comp(num):
"""
Convert from two's complement to negative.
"""
assert 0 <= num < 2**32
if num & 2**31:
return num - 2**32
else:
return num |
def construct_headers(token):
"""Construct headers for the REST API call."""
headers = {'Authorization': 'Bearer ' + token}
return headers |
def collatz(x):
"""
Generates the next term of the Collatz sequence, given the previous term x
"""
if x % 2 == 0:
return(x//2)
else:
return(3*x + 1) |
def get_intervals(l):
"""For list of lists, gets the cumulative products of the lengths"""
intervals = len(l) * [0]
# Initalize with 1
intervals[0] = 1
for k in range(1, len(l)):
intervals[k] = (len(l[k]) + 1) * intervals[k-1]
return intervals |
def get_name_and_version(filename):
"""Guess name and version of a package given its ``filename``."""
idx = filename.rfind('.tar.gz')
if idx == -1:
idx = filename.rfind('.zip')
if idx == -1:
idx = filename.rfind('.tar.bz2')
if idx == -1:
idx = filename... |
def pad(size, value):
"""Adds up to size bytes to value to make value mod size == 0"""
return (value + size - 1)/size*size |
def generate_kmers(kmerlen):
"""make a full list of k-mers
Arguments:
kmerlen -- integer, length of k-mer
Return:
a list of the full set of k-mers
"""
nts = ['A', 'C', 'G', 'T']
kmers = []
kmers.append('')
l = 0
while l < kmerlen:
imers = []
for imer in kmers:
for nt in nts:
imers.append(i... |
def chunk_string(string, length):
""" This function splits a string of text to equal chunks of text/ string
with equal length.
Args:
string: accepts a string of any length as a parameter.
length: accepts a integer as a parameter.
Returns:
The function returns a python list wit... |
def _shape_equal(shape1, shape2):
"""
Check if shape of stream are compatible.
More or less shape1==shape2 but deal with:
* shape can be list or tupple
* shape can have one dim with -1
"""
shape1 = list(shape1)
shape2 = list(shape2)
if len(shape1) != len(shape2):
return F... |
def move_coordinates(geo, idx1, idx2):
""" move the atom at position idx1 to idx2, shifting all other atoms
"""
# Get the coordinates at idx1 that are to be moved
geo = [list(x) for x in geo]
moving_coords = geo[idx1]
# move the coordinates to idx2
geo.remove(moving_coords)
geo.insert(... |
def list_of_dict_to_dict(list_of_dict, key):
"""
Converts a list of dicts to a dict of dicts based on the key provided.
Also removes the key from the nested dicts.
converts [{key: v1, k2:v12, k3:v13}, {key:v2, k2: v22, k3:v23}, ... ]
to {v1: {k2: v12, k3:v13}, v2:{k2:v22, k3:v23}, ...}
Args:
... |
def is_digit(key_name):
"""Check if a key is a digit."""
return len(key_name) == 1 and key_name.isnumeric() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.