StackUser
StackUser

Reputation: 475

Return a single value from dictionary which satisfies some condition

I have a dictionary as this:

x = {
   "Student": [
       {
        "Student Details": {
                    "name": "Alex",
                    "class": "Biology",
                    "gender": "male",
                         },
        "Nationality": "",
        "Test Score": 10.0,
        "Exam Score": 70.0,
                
        },
              ],
    }

I would like to return the exam score from this dictionary if the student details nested dictionary contains the keys names, class and gender.

The example output should be if the student details has tags as names, class and gender it should return the exam score as 70.0

I have tried this, but am not sure its doing the right this

d = ('name','class','gender')
for k,v in x.items():
    if k == 'Student Details':
        if set(d).issubset(v):
                print('yes, this student details key has tags as names, class and gender')
    print(x['Exam Score'])

Upvotes: 1

Views: 58

Answers (3)

Ram
Ram

Reputation: 4779

You are very close. Fix few indentations and your code works as expected.

x = data['Student']
d = ('name','class','gender')
for std in x:
    for k,v in x.items():
       if k == 'Student Details':
            if set(d) == set(v):
                print('yes, this student details key has tags as names, class and gender')
                print(std['Exam Score'])
yes, this student details key has tags as names, class and gender
70.0

Upvotes: 0

Alejandro A.
Alejandro A.

Reputation: 136

Your logic is not necessarily wrong, but it could be condensed a bit.

This approach uses all() which returns True if all elements in the list passed as argument are True. The argument for all() is a list comprehension that checks if each tag is in the iterable returned by x.keys(). One minor drawback is that x.keys() is computed for each tag.

TAGS = ['name', 'class', 'gender']

if all([tag in x['Student Details'].keys() for tag in TAGS]):
    return x['Exam Score']

Having said that, I'd advise you to review the schema of your data. You have a key Student at the root level, which is an array, that seems inconsistent, if it is an array it should be Students, otherwise, it should be just an object. Second, your keys are named with upper case and spaces, which is not pythonic, I'd also suggest you to change that, i.e. Student Details => student_details

Upvotes: 0

ChrisOram
ChrisOram

Reputation: 1434

A simple solution, on the assumption the structure of the data doesn't change:

expected_details = ['name','class','gender']
if all([field in expected_details for field in data["Student"][0]["Student Details"].keys()]):
    print(data["Student"][0]['Exam Score'])

Which gives:

70.0

Upvotes: 1

Related Questions