1

Python Dictionary beginner here,

@app.route('/pokemon/original/<string:name>/', methods=['GET'])
def get_poke(name):
    descrip_url = f"https://pokeapi.co/api/v2/pokemon-species/{name.lower()}"
    r = requests.get(descrip_url)
    json_blob = r.json()
    flav_text = extract_descriptive_text(json_blob)
    # clean_description = flav_text.replace("\n", " ")
    d = {"name": name, "description": flav_text}
    ordered_poke_list = OrderedDict(jsonify(d))
    return ordered_poke_list

What I want to achieve: display the key 'name' followed by 'description' inside a dictionary in the format:

{'name': variable, 'description': variable}

After some research, I've learned that Dictionaries in Python are unordered by nature but can be amended using OrderedDict. I attempted to use this via code above. Error I'm receving:

TypeError: 'Response' object is not iterable

Other attempt: I've also tried using this stackoverflow question's advice and try the dict method to no avail

d = dict(name=name,description=flav_text)
return jsonify(d)

Error: This returns description first.

Any help would be massively appreciated

Helpful info:

Jsonify

extract_description_text: grabs Pokemon description from the PokeAPI

def extract_descriptive_text(json_blob, language='en', version= 'sword'):
    text = ""
    for f in json_blob['flavor_text_entries']:
        if f['language']['name'] == language and f['version']['name'] == version:
            text = f['flavor_text']
    return text

Traceback:

Traceback (most recent call last):
  File "/Users/swapneel/Library/Python/3.8/lib/python/site-packages/flask/app.py", line 2464, in __call__
    return self.wsgi_app(environ, start_response)
  File "/Users/swapneel/Library/Python/3.8/lib/python/site-packages/flask/app.py", line 2450, in wsgi_app
    response = self.handle_exception(e)
  File "/Users/swapneel/Library/Python/3.8/lib/python/site-packages/flask_restful/__init__.py", line 272, in error_router
    return original_handler(e)
  File "/Users/swapneel/Library/Python/3.8/lib/python/site-packages/flask/app.py", line 1867, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/Users/swapneel/Library/Python/3.8/lib/python/site-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/Users/swapneel/Library/Python/3.8/lib/python/site-packages/flask/app.py", line 2447, in wsgi_app
    response = self.full_dispatch_request()
  File "/Users/swapneel/Library/Python/3.8/lib/python/site-packages/flask/app.py", line 1952, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/Users/swapneel/Library/Python/3.8/lib/python/site-packages/flask_restful/__init__.py", line 272, in error_router
    return original_handler(e)
  File "/Users/swapneel/Library/Python/3.8/lib/python/site-packages/flask/app.py", line 1821, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/Users/swapneel/Library/Python/3.8/lib/python/site-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/Users/swapneel/Library/Python/3.8/lib/python/site-packages/flask/app.py", line 1950, in full_dispatch_request
    rv = self.dispatch_request()
  File "/Users/swapneel/Library/Python/3.8/lib/python/site-packages/flask/app.py", line 1936, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/Users/swapneel/Desktop/projects/PokemonTranslation/main.py", line 49, in get_poke
    ordered_poke_list = OrderedDict(jsonify(d))
TypeError: 'Response' object is not iterable
user13641095
  • 107
  • 6
  • 1
    What is `extract_descriptive_text` and `jsonify`? Please read how to provide a [mre] and [edit] your question to include the __full__ stack trace. – Pranav Hosangadi Oct 06 '20 at 15:16
  • @PranavHosangadi Does this help? Trying to keep the post as minimal as possible – user13641095 Oct 06 '20 at 17:10
  • **Full stack trace** please. `TypeError: 'Response' object is not iterable` tells you _what_ the error is. A stack trace also contains information about _where_ the error happened. – Pranav Hosangadi Oct 06 '20 at 17:11
  • @Carcigenicate It needs to follow an output format whereby both keys value pairs are contained inside a single dictionary. – user13641095 Oct 06 '20 at 17:11
  • @PranavHosangadi Done – user13641095 Oct 06 '20 at 17:23
  • [From your link](https://www.fullstackpython.com/flask-json-jsonify-examples.html): "jsonify is a function in Flask's flask.json module. jsonify serializes data to JavaScript Object Notation (JSON) format, ***wraps it in a Response object*** with the application/json mimetype." `OrderedDict` wants an iterable such as a `list` or a `dict`, not a `Response` object – Pranav Hosangadi Oct 06 '20 at 17:25
  • @PranavHosangadi I've tried removing jsonify. The result I got was the same return I received when I tried `dict()`. `description` was first – user13641095 Oct 06 '20 at 17:30
  • [OrderedDict](https://docs.python.org/3/library/collections.html#ordereddict-objects) keeps track of the order keys were added to it. `dict` doesn't. Create the ordered dict and add keys to it directly instead of via a regular dict. – Pranav Hosangadi Oct 06 '20 at 17:32
  • @PranavHosangadi How would you add the keys after creating the `OrderedDict`? There are several different ways I've tried now and it gives me the same result as before – user13641095 Oct 06 '20 at 19:27
  • 1
    `od = OrderedDict(); od['name'] = 'Bulbasaur'; od['description'] = 'My favorite pokemon'; print(od); print(json.dumps(od))` Output: `OrderedDict([('name', 'Bulbasaur'), ('description', 'My favorite pokemon')])` // `'{"name": "Bulbasaur", "description": "My favorite pokemon"}'` – Pranav Hosangadi Oct 06 '20 at 19:32
  • @PranavHosangadi: thank you for your answer. This worked great. I also realised it was `Jsonify` that was causing my issue. I would add my keys and values to the `OrderedDict` but once I used `jsonify()` Flask serialized the JSON objects in a way that the keys are ordered and NOT via their point of insertion – user13641095 Oct 07 '20 at 07:09

0 Answers0