Home > Net >  Unable to resolve KeyError in Python using Flask
Unable to resolve KeyError in Python using Flask

Time:11-25

I continue to get this KeyError even though the key "name" obviously exists. I've attempted a couple methods to iterate through an array of dictionaries in Python with no luck. Any help is appreciated.

from flask import Flask, json, request
from werkzeug.user_agent import UserAgent

app = Flask(__name__)

users = [
    {"name:": "bitley",
     "age": 5000,
     "items": [
         {"name:": "toyota"},
         {"name": "camry"}
     ]
    
    }
]


#/GET a user by ID
@app.route('/users/<string:name>')
def get_user_by_name(name):
     #check to see if the user exists 
    for user in users:
        if user['name'] == 'name':
           return json.jsonify(users)
    return json.jsonify({"message: " "user not found.."})

Error

    if user['name'] == 'name':
KeyError: 'name'

CodePudding user response:

It's because there is an extra colon "name:":. What I think you mean is "name":.
And probably you mean return json.jsonify({"message:" "user not found.."}) instead of return json.jsonify({"message": "user not found.."}).
And if user['name'] == name: instead of if user['name'] == 'name':.

CodePudding user response:

Your problem is when you create your users list, you have an extra colon in in the name key, it should be:

users = [
    {"name": "bitley",
     "age": 5000,
     "items": [
         {"name:": "toyota"},
         {"name": "camry"}
     ]
    }
]

CodePudding user response:

The problem is not only the extra colon but also how you access the data in the list because, in list indices, you can only use integers or slices, not strings. Moreover, when you check the username, it should be a variable and not a string, otherwise, it will never pass through. So it should be:

from flask import Flask, json, request

app = Flask(__name__)

users = [
    {"name": "bitley",
     "age": 5000,
     "items": [
         {"name:": "toyota"},
         {"name": "camry"}
     ]
    
    }
]

@app.route('/users/<string:name>')
def get_user_by_name(name):
     #check to see if the user exists 
    for user in users:
        if users[0]['name'] == name:
           return json.jsonify(users)
    return json.jsonify({"message: " "user not found.."})
  • Related