简体   繁体   中英

Search for value in list in python dictionary

I want to be able to get the name of a person given a nickname (all nicknames are unique). A person can have multiple nicknames. I was thinking of using a dictionary like the following

nicknames = {
    'lebron james': ['king james', 'lbj'],
    'dwayne johnson': ['rocky', 'the rock', 'brahma bull']
}

So for instance, given a string 'rocky' , I want to be able to return 'dwayne johnson' . Is this kind of data structure the most optimal way to store the name=>nicknames pairing? Or is there a better way to store the data to make searching more efficient?

Your dictionary is the wrong way around. If nicknames are unique, use them as keys.

>>> nicknames = {
...:    'lebron james': ['king james', 'lbj'],
...:    'dwayne johnson': ['rocky', 'the rock', 'brahma bull']
...:}
>>> 
>>> nicknames = {nick:real for real, lst in nicknames.items() for nick in lst}
>>> nicknames
{'brahma bull': 'dwayne johnson',
 'king james': 'lebron james',
 'lbj': 'lebron james',
 'rocky': 'dwayne johnson',
 'the rock': 'dwayne johnson'}
>>> 
>>> nicknames['rocky']
'dwayne johnson'

I thinkg the answer form @timgeb is correct. But if transforming the dictionary is not an option you can always search for it, which I think would have the same performance implications as transforming first:

nicknames_by_name = {...}
def find_name(nickname_to_find);
    for name, nicknames in nicknames_by_name.items():
        for nickname in nicknames:
            if nickname == nickname_to_find:
                return name

That should do the trick without transforming the dictionary first. Yet again, if the search is going to happen more than once, transforming the dictionary once before any search happens will make subsequent searches faster, although that only applies if the nicknames are unique.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM