Didn't use Python in a while..having some problems while sorting a dictionary
i have a dictionary called bad_functions
holding ~500 pairs
example : {'lambda_1': 0, 'lambda_2': 0}
code :
from contextlib import redirect_stdout
import subprocess
import json
# deafult region is us-east-2
region="us-east-2"
# command for getting all lambdas lambdas in eu-east-2
list_lambda_command = "aws lambda list-functions --region {region} --query 'Functions[].FunctionName' --output json"
# command for getting a specific lambda cuoncurrency
lambda_concurrency="aws lambda get-function-concurrency --function-name {function_name}"
# running the first aws cli command on host and load to list object
lambda_json_output = subprocess.check_output(['bash','-c', list_lambda_command.format(region=region)]).decode()
lambda_list=json.loads(lambda_json_output)
# empty list for incoming 'bad' lambda's results
bad_functions={}
for function in lambda_list:
# getting lambda funcations with unreserved concurreny value into a dict
try:
output=subprocess.check_output(['bash','-c', lambda_concurrency.format(function_name=function)]).decode()
current_lambda_concurrency=json.loads(output)
except:
bad_functions[f'{function}']="unreserved"
continue
# getting lambda funcations with 'bad' concurreny value value into a dict
current_concurrency=current_lambda_concurrency['ReservedConcurrentExecutions']
if current_concurrency != 1:
bad_functions[f'{function}']=int(current_concurrency)
# sorting the dic by value
print(bad_functions)
bad_functions_sorted={k: v for k, v in sorted(bad_functions.items(), key=lambda item: item[1])}
ERROR i get :
File "script.py", line 40, in <module>
bad_functions_sorted={k: v for k, v in sorted(bad_functions.items(), key=lambda item: item[1])}
TypeError: '<' not supported between instances of 'str' and 'int'
CodePudding user response:
My bad,didnt give enough information in the question.
A possible output could've been
{'lambda_1': 0, 'lambda_2': 0,, 'lambda_2': "unreserved}
So the ERROR TypeError: '<' not supported between instances of 'str' and 'int'
makes a lot of sense
What i did to solve this is to separate them to 2 different dicts
for function in lambda_list:
try:
output=subprocess.check_output(['bash','-c', lambda_concurrency.format(function_name=function)]).decode()
current_lambda_concurrency=json.loads(output)
except:
unreserved_function[f'{function}']="unreserved"
continue
current_concurrency=current_lambda_concurrency['ReservedConcurrentExecutions']
if current_concurrency != 1:
concurrency_functions[f'{function}']=int(current_concurrency)
And only sorted the 'int' dict
bad_functions_sorted={k: v for k, v in sorted(concurrency_functions.items(), key=lambda item: item[1])}