Kwistech
Kwistech

Reputation: 47

How to input a number which will result in searching a list then a dictionary for confirmation

So I keep getting the error "TypeError: 'int' object is unsubscriptable" for my code. What I want to do is have a number as an input and then have a function that searches first a list, then a dictionary for that number. If that number is in the dictionary, then return some info. I think I know why the error message pops up, but I am asking for an alternative to do what I want.

item1 = {
    "name": "Item 1",
    "code": 1001,
}

item2 = {
    "name": "Item 2",
    "code": 1002,
}

item3 = {
    "name": "Item 3",
    "code": 1003,
}

produce = [item1, item2, item3]

def produce_info_code(x):
    print
    produce_name = input("Enter Produce code [eg. 1234]: ")
    if produce_name["code"] in x:
        return "Name: %s" % produce_name["name"], "Code: %s" % produce_name["code]

print produce_info_code(produce)

Any help is appreciated!

Upvotes: 1

Views: 41

Answers (2)

Pankaj Singhal
Pankaj Singhal

Reputation: 16043

You can also use Generator Expressions like following:

def produce_info_code(x):
    produce_name = int(input("Enter Produce code [eg. 1234]: "))
    return next((("Name: %s, Code: %d" % (item["name"],produce_name)) for item in produce if item["code"] == produce_name),None)

Upvotes: 0

Ozgur Vatansever
Ozgur Vatansever

Reputation: 52153

I don't think you posted your entire code because according to this, there is no way you can get the above error. Anyway, the actual problem is, the returned value from input() is a str type which is not subscriptable.

def produce_info_code(x):
    produce_name = int(input("Enter Produce code [eg. 1234]: "))
    for dct in x:
        if produce_name == dct.get("code")
            return "Name: %s" % dct["name"], "Code: %d" % produce_name
    return None

Upvotes: 1

Related Questions