Python: How to filter dictionary?

Viewed 44

I want to achieve the following, but using dictionary.

name_selected = "Jason"

if name_selected == "John":
    age = 10
    gender = "Male"
elif name_selected == "Jason":
    age = 20
    gender = "Male"

print(age, gender)
data = {"name": ["John", "Jason"],
         "age": [10, 20],
      "gender": ["Male", "Male"]}
2 Answers

That's a poor data organization. It would be better if you made the names the dictionary keys:

data = {
    "John": { "age": 10, "gender": "Male"},
    "Jason": { "age": 20, "gender": "Male"}
}

age = data[name_selected]["age"]
gender = data[name_selected]["gender"]

But if you're stuck with your data structure, you can use index() to get the index in the name element, then use that to get the corresponding values in the other elements.

try:
    index = data['name'].index(name_selected)
    age = data['age'][index]
    gender = data['gender'][index]
except:
    print(f'{name_selected} not found')

Since you're testing name_selected == ..., the possible values of name_selected are the dictionaries you want. Dictionaries are the structure that replaces if-elif lookup on a variable.

Given that, you can store the remaining data in any number of ways. Here's a tuple that you can unpack:

data = {'John': (10, 'Male'),
        'Jason': (20, 'Male')}

Then you can do

age, gender = data[name_selected]

You can extend the idea with another nested dictionary:

data = {'John': {
    'age': 10, 'gender': 'Male'},
        'Jason': {
    'age': 20, 'gender': 'Male'}
}

Now it might be better not to unpack:

person = data[name_selected]
# use person ['age'] and person['gender']

A more application-specific solution would be to make the values custom objects (like a collections.namedtuple) that would let you access the data for an individual as attributes.

Related