Last active
September 7, 2024 15:56
-
-
Save fastfingertips/3ca418fef68f7d42c0172d5bccad26a8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
test_list = ['2024', '01', '23', ''] | |
keys = list(range(len(test_list))) | |
keys_2 = list(range(len(test_list) - 1)) | |
# 1 | |
try: | |
print(json.dumps( | |
dict(zip( | |
keys, | |
map(int, test_list) | |
)), | |
indent=4 | |
)) | |
except ValueError as e: | |
print("Error: " + str(e)) | |
# 2 | |
print(json.dumps( | |
dict(zip( | |
keys_2, | |
map(int,test_list) | |
)) | |
, indent=4 | |
)) | |
# 3 | |
print(json.dumps( | |
dict(zip( | |
keys, | |
map(int, [value for i, value in enumerate(test_list) if value]) | |
)) | |
, indent=4 | |
)) | |
# 4 | |
x = {} | |
for i, value in enumerate(test_list): | |
if value: x[i] = int(value) | |
print(json.dumps(x, indent=4)) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
def convert_list_to_dict(keys, values): | |
"""Convert a list of values to a dictionary using specified keys.""" | |
return dict(zip(keys, values)) | |
def main(): | |
"""Main function to execute the conversion and output.""" | |
test_list = ['2024', '01', '23', ''] | |
keys = list(range(len(test_list))) | |
keys_2 = list(range(len(test_list) - 1)) | |
# 1. Attempt to convert the list to a dictionary with integer values | |
try: | |
result_1 = convert_list_to_dict( | |
keys, | |
map(int, test_list) | |
) | |
print(json.dumps(result_1, indent=4)) | |
except ValueError as e: | |
print(f"Error: {e}") | |
# 2. Attempt with reduced number of keys | |
try: | |
result_2 = convert_list_to_dict( | |
keys_2, | |
map(int, test_list) | |
) | |
print(json.dumps(result_2, indent=4)) | |
except ValueError as e: | |
print(f"Error: {e}") | |
# 3. Filter out empty strings before converting | |
try: | |
result_3 = convert_list_to_dict( | |
keys, | |
map(int, [value for value in test_list if value]) | |
) | |
print(json.dumps(result_3, indent=4)) | |
except ValueError as e: | |
print(f"Error: {e}") | |
# 4. Use a loop to build the dictionary, filtering out empty values | |
result_4 = {} | |
for i, value in enumerate(test_list): | |
if value: | |
result_4[i] = int(value) | |
print(json.dumps(result_4, indent=4)) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment