1

I'm relatively new to this so please excuse me if I'm missing something very obvious :)

I'm trying to print code, and value of the attached Json file.

for example

for item in dataxchjs['data']:
    print(item) 

works perfectly, and prints me AED as the first value

But

for item in dataxchjs['data']:
    print(item["code"], item["value"])

returns the error code

, line 47, in <module>
    print(item["code"], item["value"])
TypeError: string indices must be integers

What am I missing?

json file:

{
 "meta": {
  "last_updated_at": "2022-04-04T23:59:59Z"
 },
 "data": {
  "AED": {
   "code": "AED",
   "value": 3.67321
  },
  "AFN": {
   "code": "AFN",
   "value": 89.00134
  },
...
}

Thank you all very much

please don't dislike the post I really tried to understand the problem myself for a while now

3
  • 1
    Use for key, item in dataxchjs['data'].items() or for item in dataxchjs['data'].values() Commented Apr 5, 2022 at 12:14
  • data is a dict. when you iterate over dict, you iterate over dict keys. In your case - str AED, AFN, etc. Commented Apr 5, 2022 at 12:14
  • Is every json response/object fundamentally a dictionary? Commented Apr 5, 2022 at 12:18

3 Answers 3

2

The for ... in dictionary iterator will only iterate over the keys.

To get keys and their values (in this case AED,{"code": "AED", "value": 3.67321} and AEDAFNcode": "AFN", "value": 89.00134) use for key,value in yourdict.items()

Sign up to request clarification or add additional context in comments.

Comments

0

In Python, a JSON file is usually converted to a dictionary.

Use the .items() method to extract the key and value variables while looping. Your current method gives you the keys (strings "AFN", "AED" etc) only.

for key, item in dataxchjs['data'].items():
    print(key, item["value"])

About second question.

Python has an in keyword. See if that does the job for you?

def find_in_data(key):
    return dataxchjs['data'][key] if key in dataxchjs['data'] else None

print(find_in_data('AED'))
print(find_in_data('XDR'))

2 Comments

Does anyone know how I could find the corresponding value if i use the code to iterate throught the dictionary? my idea was 'code' def find_value(currency): for key, value in dataxchjs['data'].items(): return value if key == currency in dataxchjs['data'].items() else exit("not found")'
@PetersServers, this is technically a separate question, and it would be better if you searched online or made a separate post. However, since you're new here, I'll edit the solution into my current solution. Please make sure to accept the solution that works for you, as that helps people who search for this question in the future.
0
is_dict = {
    "meta": {
        "last_updated_at": "2022-04-04T23:59:59Z"
    },
    "data": {
        "AED": {
            "code": "AED",
            "value": 3.67321
        },
        "AFN": {
            "code": "AFN",
            "value": 89.00134
        }
    }
}

### Like this:

for x in is_dict['data'].values():
    for key, value in x.items():
        if key == "code":
            print(value)
        elif key == "value":
            print(value)

### Or like this:

for x in is_dict['data'].values():
    print(x["code"])
    print(x["value"])

### Or this for errors:

data = is_dict.get('data')

if data:
    for x in data.values():
        print(x.get("code"))
        print(x.get("value"))

JSON package converts file to a python dictionary.
Navigate in dictionary through the loop with items(), values() and keys() methods of dictionary, or use indexes(keys) as dictionary["key"], or to exclude errors on not existing keys use get() method as dictionary.get("key").

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.