0

I have a dictionary imported from a JSON file:

"teachers": [
        {
            "fname": "George",
            "lname": "Edward",
            "val": true
        },
        {
            "fname": "David",
            "lname": "Smith",
            "val": true
        }]

Assuming a user inputs "David", how do I return "Smith" and true? Are dictionaries even the right thing to use here?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • See https://docs.python.org/3/tutorial/datastructures.html#dictionaries. Note you'll need to *parse* the JSON to a dictionary, you can use the `json` module in the standard library. – jonrsharpe Nov 26 '20 at 17:19

1 Answers1

1

If you have JSON file with the structure you gave us, Python will parse this to the list of dictionaries.

You can use a function like this:

def find_name(teachers, name):
    for teacher in teachers:
        if teacher['fname'] == name:
            return teacher

Thanks to this you will be able to search for the name and receive a dict that contains that name.

>>> teachers = [{'fname': 'George', 'lname': 'Edward', 'val': True}, {'fname': 'David', 'lname': 'Smith', 'val': True}]

# then you can search for any name
>>> find_name(teachers, 'David')
{'fname': 'David', 'lname': 'Smith', 'val': True}

# you can also access other keys of the dict:
>>> george = find_name(teachers, 'George')
>>> george['lname']
'Edward'
>>> george['val']
True

EDIT: If you want to get O(1) lookup using dictionaries, you could modify your data so that teacher name is a dict key.

teachers = {  # notice that teachers are now a dict
  "David": {"lname": "Smith", "val": True},
  "George": {"lname": "Edward", "val": True},
}

And use that function

def get_teacher(teachers, name):
    return teachers.get(name)

But again, you need different JSON structure in that case.

umat
  • 607
  • 1
  • 13
  • 25