1

Lets say I have a basic flask program...

lis = [1, 2, 3, 4]
dict1 = defaultdict(list)
dict1["key"].append("Hello")

@app.route("/list/<string:index>")
def l(index):
    return lis[index]

@app.route("/dictionary/<string:key>")
def d(key):
    return dict1[key]

Why is the first valid, and the second invalid?

How do I return all of the items in the dictionary?

  • are you actually passing a variable `key` ? because `dict["key"]` and `dict[key]` are not the same. your error message should help too if you run with debug mode on. edit: Ah, i see your update now. alright. – Paritosh Singh Dec 19 '18 at 20:23

2 Answers2

2

The issue is that flask is expecting a simple string or callable object in the responses, as it requires passing the values around. A dictionary is not a callable object, and you have to convert it to a form flask can pass around using either json.dumps and setting the appropriate Content-type headers ('application/json' in this case) or just using jsonify that does the hard work for you. Jsonify Docs

import flask
from flask import request, jsonify #import jsonify
from collections import defaultdict
app = flask.Flask(__name__)
app.config["DEBUG"] = True


lis = [1, 2, 3, 4]
dict1 = defaultdict(list)
dict1.setdefault("key", []).append("Hello") #you do not need to setdefault if you're already using a defaultdict, but this does not raise any errors.
dict2 = {"a":"res"}

@app.route("/list/<string:index>")
def l(index):
    return lis[index]

@app.route("/dictionary/<string:key>")
def d(key):
    return jsonify(dict1[key]) #use it to handle dictionary

app.run()
Paritosh Singh
  • 6,034
  • 2
  • 14
  • 33
0

Dot not name your variable as list or dict as they shadow built ins. Try the code below. Link to the docs

lis = [1, 2, 3, 4]
dict1 = defaultdict(list)
dict1['key'].append("Hello")

If you want to get all the items of the dict1

dict1.items()

It contains a good explanation of how defaultdict works How does collections.defaultdict work?

mad_
  • 8,121
  • 2
  • 25
  • 40
  • I edited my example to more accurately reflect my program –  Dec 19 '18 at 20:26
  • still you are using in the wrong manner. check docs attached. Thanks – mad_ Dec 19 '18 at 20:27
  • I still get the error: "TypeError: 'dict_items' object is not callable" –  Dec 19 '18 at 20:34
  • Also, I don't want to get all the items of dict1, just all of the values associated with the key that is passed in. Shouldn't I just be able to use: dict1['key']? –  Dec 19 '18 at 20:39
  • Your question and code are tangentials. yes you should get THE value from dict1['key'] but you have just one str object 'hello' mapped to the key so that should be returned. – mad_ Dec 19 '18 at 20:45