Home > Back-end >  How to use python dictionary and perform arithmetic calculation in for loop condition - JSON output
How to use python dictionary and perform arithmetic calculation in for loop condition - JSON output

Time:08-15

I have written code to get data from an API. I was able to parse the JSON data from the API. The output is a JSON response.

Im trying to :

  • retrieve corecount and ThreadsPerCore values.
  • then will multiply corecount x ThreadsPerCore = vcpus for respective instances.
  • and sum up all vcpus of instances.

How can I write code that does this ?

I have got a workaround to retrieve the values from the json output and im trying to understand how to use python dictionary in this case to perform multiply and addition of the values obtained.

here is the JSON output structure (in this example there is 3 set of objects inside the structure, but in real case the number of objects may vary - hence used a 'for' loop in my code:

[
    [
        {
            "CoreCount": 4,
            "ThreadsPerCore": 2
        }
    ],
    [
        {
            "CoreCount": 8,
            "ThreadsPerCore": 2
        }
    ],
    [
        {
            "CoreCount": 4,
            "ThreadsPerCore": 2
        }
    ]
]

My code to retrieve CoreCount and ThreadsPerCore values is

from shell import run_command_str
import json
status_command = "aws ec2 describe-instances --filters Name=instance-state-name,Values=running --query 'Reservations[*].Instances[*].CpuOptions' --output json --region eu-west-3"
status = run_command_str(command=status_command, shell_command=True)
status1 = json.loads(status)
print (status1)
print("Length", len(status1))
for i in range(len(status1)):
    print ("printing i", i)
    corecount = print("printing corecount", status1[i][0]["CoreCount"])
    threadspercore = print("printing Threadspercore", status1[i][0]["ThreadsPerCore"])

the output of this code is:

[[{'CoreCount': 4, 'ThreadsPerCore': 2}], [{'CoreCount': 8, 'ThreadsPerCore': 2}], [{'CoreCount': 4, 'ThreadsPerCore': 2}]]

Length 5
printing i 0
printing corecount 4
printing Threadspercore 2
printing i 1
printing corecount 8
printing Threadspercore 2
printing i 2
printing corecount 4
printing Threadspercore 2

CodePudding user response:

  • retrieve corecount and ThreadsPerCore values.
  • then will multiply corecount x ThreadsPerCore = vcpus for respective instances.
  • and sum up all vcpus of instances.
# NOTE: this represents how you get your data, as in the code to read
#       in JSON values. This is simply how to extract the data from the list.
data = [[{'CoreCount': 4, 'ThreadsPerCore': 2}], [{'CoreCount': 8, 'ThreadsPerCore': 2}], [{'CoreCount': 4, 'ThreadsPerCore': 2}]]

vcpu_values = list()
total_vcpus = 0

for list_dict in data:
    my_dict = list_dict[0]
    corecount = my_dict["CoreCount"]
    threads_per_core = my_dict["ThreadsPerCore"]
    
    vcpus = corecount * threads_per_core
    
    vcpu_values.append(vcpus)
    
    total_vcpus  = vcpus
    
print(f"Total VCPUS: {total_vcpus}")  # print total VCPUs
print(f"VCPUs per: ", vcpu_values)    # print VCPUs per element in the list

CodePudding user response:

If I am trying to get some values from looping over a collect and I need those individual values, I would assign an empty list to a variable just before the loop.

In this case, I'm not clear on what you are referring to when you say you have 3 sets of objects. In the json output, there are 3 lists inside of one list and in each of those nested lists there is one instance object represented by json. I am unsure if the number of nested lists will change, or if it is the number of objects within that is variable.

For the sake of this answer, I will assume there will only be 3 nested lists with a variable number of objects in each. If I assumed wrong, please clarify in your question and I will update my answer.

# ommitted code
status1 = json.loads(status)
# omitted code
instance_1_vcpu_counts = []
instance_2_vcpu_counts = []
instance_3_vcpu_counts = []

for i in range(len(status1[0])):
    cores = status1[0][i].get("CoreCount")
    threads =status1[0][i].get("ThreadsPerCore")
    instance_1_vcpu_counts.append(cores*threads)   

for i in range(len(status1[1])):
    cores = status1[1][i].get("CoreCount")
    threads =status1[1][i].get("ThreadsPerCore")
    instance_2_vcpu_counts.append(cores*threads)

for i in range(len(status1[2])):
    cores = status1[2][i].get("CoreCount")
    threads =status1[2][i].get("ThreadsPerCore")
    instance_3_vcpu_counts.append(cores*threads)

After that, you have 3 lists of vcpu counts, one list for each machine in an instance. It is easy to get the total vcpus per instance, you can use the built in sum() function.


instance_1_vcpu_total = sum(instance_1_vcpu_counts)

And for the total vcpu count across all instances, just add the sums together.

  • Related