print(f"input_vars: {input_vars}")
print(f"original_input_vars: {original_input_vars}")
print(f"returned_output_vars: {returned_output_vars}")
print(f"true_output_vars: {true_output_vars}")| Task | Method | Code Snippet | Notes |
|---|---|---|---|
| Dictionary Get | for dictionary safe get | my_dict = {'a': 1, 'b': 2}# Key exists:value_a = my_dict.get('a', 0)1# Key does not exist, returns default (0)value_c = my_dict.get('c', 0)0# Key does not exist, returns None by default:value_d = my_dict.get('d')None |
|
| Dictionary modification | Add item | mydict['new_key'] = 'value' |
|
| Dictionary modification | update with multiple | mydict.update( {'key':'v', 'key1':'v1'} ) |
|
| Dictionary Iteration | Key-Value Pairs (Tuple) | types = [(k, v) for k, v in pois.items()] |
Output - list of tuples |
| Dictionary Iteration | Key-Value Pairs (List) | types = [[k, v] for k, v in pois.items()] |
Output - list of lists |
| Dictionary Iteration | Key-Value Pairs (List) | types = [k:v for k, v in pois.items()] |
Output - dictionary |
| Extracting Keys | Comprehension | types = [k for k, v in pois.items()] |
|
| Extracting Keys | Simpler Method | types = list(pois.keys()) |
|
| Extracting Values | Comprehension | types = [v for k, v in pois.items()] |
|
| Extracting Values | Simpler Method | types = list(pois.values()) |
|
| Unpacking | Keys and Values Separately | keys, values = zip(*pois.items()) |
|
| Reverse Dictionary | Comprehension | reversed_pois = {v: k for k, v in pois.items()} | If original dictionary has duplicate values the reversed dictionary will only keep the last key processed for that value |
| Count Occorurences | Count freq | word_list = ['dog', 'cat', 'horse', 'dog']word_counts = Counter(word_list) print(word_counts)#Output: Counter({'dog': 2, 'cat': 1, 'horse': 1}) |
| Task | Method | Code Snippet |
|---|---|---|
| Reverse a list | list reverse | new_list = reversed(old_list) |
| List Append | add items | list_sample.append(5) |
| List extend | add multiple items | list_sample.extend(list2) |
| List Insert | Inserts at a position | my_list.insert(1, 'banana') |
| List Comprehension | Nested Loop Syntax | [expression for outer in outer_list for inner in outer] |
| Flattening Lists | Flatten nested list | flat_list = [item for sublist in lst for item in sublist] |
| Use Filter | Use filter in iteration | def is_even(x): # Returns Trueonly ifx is an even integer return (x % 2) == 0# Filter a sequence, keeping just the even values:for val in filter(is_even, [3, 6, 8, 2, 7, 1, 4, 9, 5, 0]): print(val, end=' ') |
| Enumerate | to get index and value | for index, fruit in enumerate(fruits): print(f"Index {index}: {fruit}") |
| List Remove | [ num for num in L if num != x] |
| Task | Method | Code Snippet | Notes |
|---|---|---|---|
| Convert integer to binary | use bin | bin(10) | Returns '0b1010'; the 0b prefix indicates binary. <class 'str'> |
| Convert integer to binary | Format string | f"{10:b}" | Returns '1010'; removes the 0b prefix automatically. |
| Convert to Float | float | float(val) |
| Task | Method / Operator | Code Snippet | Logic / Description |
|---|---|---|---|
| Bitwise Operation | Left Shift | x << y | Returns x with bits shifted left by y places. Same as x * 2**y. New bits on the right are zeros. |
| Bitwise Operation | Right Shift | x >> y | Returns x with bits shifted right by y places. Same as x // 2**y. New bits on the right are zeros. |
| Bitwise AND | & |
a & b |
Sets bit to 1 if both bits are 1. |
| Bitwise OR | | |
a | b |
Sets bit to 1 if one of the bits is 1. |
| Bitwise XOR | ^ |
a ^ b |
Sets bit to 1 if only one of the bits is 1. |
| Bitwise NOT | ~ |
~a |
Inverts all the bits. |
| Task | Method / Operator | Code Snippet | Logic / Description |
|---|---|---|---|
| RegEx Split | Split based on pattern | re.split(pattern, string, maxsplit=0, flags=0) |
splits based on the given pattern |
| RegEx Findall | Returns a list based on the pattern | re.findall(pattern, string) |
is ideal when you need to extract all occurrences of a pattern from a text, such as collecting all the numbers, dates, or email addresses in a document. |
| RegEx Search | is useful for general-purpose scanning when you only need the first instance of a pattern, like finding the first email address in a log file. | ||
| RegEx Match | is best for input validation where the entire string needs to follow a specific starting format, such as checking for a specific file prefix or a country code in a phone number. |
| Task | Method / Operator | Code Snippet | Logic / Description |
|---|
| Task | Method / Operator | Code Snippet | Logic / Description |
|---|---|---|---|
| Format string with thousand separator | Format with specified separator | formatted_streams = f'{streams_avg:,}' |
Formats it with , as separator |
| Remove white space from string | my_string = " Hello World "trimmed_string = my_string.strip() |
||
| String Concatination | out_string = f'{string1}{string2}' |
| Task | Method / Operator | Code Snippet | Logic / Description |
|---|---|---|---|
| Floor Fraction | Floor the fraction | math.floor(a/b) | |
| Ceil Fraction | Ceil a fraction | math.ceil(a/b) | |
| Average | No built in method | ( a + b + c ) / 3 | |
| Min | import mathmin(my_list) |
||
| Max | import mathmax(my_list) |
| Task | Method / Operator | Code Snippet | Logic / Description |
|---|---|---|---|
| Set Intersection | set1.intersection(set2) |
Understanding
zip(*...)for UnpackingThe expression
keys, values = zip(*pois.items())is a common Python idiom used to "unzip" a dictionary into two separate collections.1. The Components
pois.items(): Returns a view of the dictionary as a list-like collection of tuples, e.g.,[('a', 1), ('b', 2)].*): When placed before a collection, it "unpacks" the contents as separate arguments. Instead of passing one list to the function, it passes each tuple individually:zip(('a', 1), ('b', 2)).zip()Function: Takes the first element from every tuple (the keys) and groups them, then takes the second element from every tuple (the values) and groups them.2. The Transformation
[('key1', 'val1'), ('key2', 'val2')]zip(*...):('key1', 'key2')and('val1', 'val2')3. Final Assignment
The results are assigned to the variables
keysandvalues. By wrapping them inlist(), you convert these tuples into mutable lists for further use: