-1

I'm sending request to an API using python's requests module and the response is in JSON (can be called dictionary right?)

If I do

for i in response:
    print(i)

It would only print the key (the parameter) and not the value, how to get both as output. Thanks.

Jam
  • 7
  • 1
  • JSON can be *decoded* into a `dict` (or a `list`, or a `str`, or an `int`, etc). Until you decode it, JSON is just a *string*. Given your description, you have already decoded the JSON, so the fact that your `dict` came from a JSON value is no longer relevant to the question. – chepner Jan 11 '20 at 14:35

1 Answers1

0

You can call items to loop over the key/value pairs at the same time.

for key,value in response.items():
    print(key, value)

The items method returns an iterator over the key/value pairs of a dictionary.

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
  • i did the exact same thing without `iteritems` what is it? – Jam Jan 11 '20 at 14:37
  • @Jam `iter(response)` (which is how the `for` loop gets an iterator from the iterable you use) returns an iterator over just the keys of the `dict`. – chepner Jan 11 '20 at 14:38
  • Yes, it worked but can anyone please exaplain what is `items` here? – Jam Jan 11 '20 at 14:39
  • 2
    [As documented](https://docs.python.org/3/library/stdtypes.html#dict.items), `items()` returns an iterable whose iterator yields tuples of keys and their associated values. – chepner Jan 11 '20 at 14:39
  • `iteritems()` was what it was called in Python 2. – tripleee Jan 11 '20 at 14:56