Searching the python dictionary of dictionaries

I have a dictionary dictionary called data_dict

. This is how it looks:

{'UMANOFF ADAM S': {'total_stock_value': 'NaN', 'loans': 'NaN', 'salary': 288589},
'YEAP SOON': {'total_stock_value': 192758, 'loans': 'NaN', 'salary': 'NaN'},
'PIPER GREGORY F': {'total_stock_value': 880290, 'loans': 1452356, 'salary': 19791},
'Jack S': {'total_stock_value': 88000, 'loans': 'NaN', 'salary': 288589}
}

      

This is mainly the format

{Person Name : Dictionary of that person attributes}

      

I am trying to find the name of a person whose salary is specific to X. Specifically in the above example - say I am trying to find the name of individuals whose salary is 288589. I expect all names whose salary is 288589.

I wrote the following generic function that will take a lookup key and value and return the names of the individuals for which this key is true.

def search_person_by_attribute(attribute, value):
    person_names = []

    for person, attributes_dict in data_dict.items():
        if attributes_dict[attribute] == value:
            person_names.append(person)

    return person_names

      

This method succeeds

results = search_person_by_attribute("salary", 288589)
print(results)

      

and printing

['UMANOFF ADAM S','Jack S']

      

But somehow I feel like it's a long way to go. Is there a better / shorter / more pythonic way to do this?

If you can also indicate the effectiveness (in terms of time complexity) of mine, and also the solution you suggest would be a great bonus.

+3


source to share


1 answer


I would suggest something like this, which I think is not just shorter, but more readable than your version:

def search_person_by_attribute(d, attribute, value):
    return [name for name in d if d[name][attribute] == value]

      



It works exactly the same as yours, but requires a dictionary as an extra parameter, because I think the best style is:

>>> search_person_by_attribute(d, "salary", 288589)
['UMANOFF ADAM S', 'Jack S']

      

+5


source







All Articles