0

I am trying to update same dictionary keys at different index in a list using a for loop. I am not sure if this is even an allowed format/way to do that with python code. Any help will be greatly appreciated.

rc_description_final=["Apple","Orange", "Pineapple"]
rc_action_final = ["Red", "Fruit", "Yellow"]
k=0
while k < len(IDs):
    temp={}
    rc = {}
    temp['Rate'] = [rc]
    d = 0
    print(rc_description_final)
    print(len(rc_description_final))
    while d < len(rc_description_final):

        temp['Rate'][d]['Description'] = rc_description_final[d]

        temp['Rate'][d]['Action'] = rc_action_final[d]

        temp['Rate'].append(rc)

        d = d + 1
    json.dumps(temp)
    print(json.dumps(temp))
    k = k + 1

I expect the output as:

{
    "Rate Limits": [
      {
        "Description": "Apple",
        "Action": "Red"
      },
      {
        "Description": "Orange",
        "Action": "Fruit"
      },
      {
        "Description": "Pinapple",
        "Action": "Yellow"
      }
    ]
}

But I am getting the output as:

{
    "Rate Limits": [
    {
        "Description": "Pinapple",
        "Action": "Yellow"
     },
    {
        "Description": "Pinapple",
        "Action": "Yellow"
     },
    {
        "Description": "Pinapple",
        "Action": "Yellow"
     }
    ]
}

1 Answer 1

1

In your case I found the issue at the "temp['Rate'] = [rc]". So when the temp['Rate'] change then the rc value will automatically change. which leads you to this output.

Here is my code for your references:

import json

rc_description_final=["Apple","Orange", "Pineapple"]
rc_action_final = ["Red", "Fruit", "Yellow"]
k=0
while k < 1:
  temp={}
  temp['Rate'] = []
  d = 0
  print(rc_description_final)
  print(len(rc_description_final))
  while d < len(rc_description_final):
    description_dict = {}

    description_dict['Description'] = rc_description_final[d]
    description_dict['Action'] = rc_action_final[d]

    temp['Rate'].append(description_dict)

    d = d + 1
json.dumps(temp)
print(json.dumps(temp))
k = k + 1
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.