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
CodePudding user response:
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()
CodePudding user response:
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"])
CodePudding user response:
dictis = {
"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 dictis['data'].values():
for key, value in x.items():
if key == "code":
print(value)
elif key == "value":
print(value)
### Or like this:
for x in dictis['data'].values():
print(x["code"])
print(x["value"])
### Or this for errors:
data = dictis.get("data")
if data:
for x in data.values():
print(x.get("code"))
print(x.get("value"))