3

I have a JSON and I want to access the keys in "rates". This is the aforementioned JSON:

currency = '''
{
  "rates": {
    "CNY": 7.6588,
    "BGN": 1.9558,
    "USD": 1.114
  },
  "base": "EUR",
  "date": "2019-07-24"
}
'''

qwe = json.loads(currency)

When i try

for x in qwe['rates']:
    print(x)

I get the values CNY, BGN, USD without the keys.

But also when I try print(qwe['rates']) I get {'CNY': 7.6588, 'BGN': 1.9558, 'USD': 1.114}

My idea is to specify the keys for each value

Miroslav
  • 133
  • 1
  • 2
  • `I get the values CNY, BGN, USD without the keys.` those ARE the keys. ;) E.g. key is 'CNY', value is '7.6588'. You can do `for key, value in qwe['rates'].items():` to get both key and value at once. – h4z3 Jul 25 '19 at 14:31
  • "I get the values CNY, BGN, USD without the keys." Um, those *are* the keys. But the difference here is that a dictionary iterator only provides the keys, not key/value pairs. `print` treats `qwe['rates']` as a *string*, not an iterator. – chepner Jul 25 '19 at 14:31
  • Possible duplicate of [Iterating over dictionaries using 'for' loops](https://stackoverflow.com/questions/3294889/iterating-over-dictionaries-using-for-loops) – Mike Scotty Jul 25 '19 at 14:43
  • Ah my mistake :D But THANKS a lot ! :) – Miroslav Jul 25 '19 at 14:58

3 Answers3

2
qwe = json.loads(currency)
for key, value in qwe['rates'].items():
    # do something with 'key' here
Joshua Schlichting
  • 3,110
  • 6
  • 28
  • 54
2

To access the value you have to print qwe['rates'][x]

for x in qwe['rates']:
  print(qwe['rates'][x])

Output

7.6588
1.9558
1.114
bcosta12
  • 2,364
  • 16
  • 28
0

You should use the .items() dict method:

for key, value in qwe['rates'].items():
    print(key, value)
Leogout
  • 1,187
  • 1
  • 13
  • 32