Search for value in list in python dictionary

余生长醉 提交于 2021-02-05 06:42:26

问题


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?


回答1:


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'



回答2:


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.



来源:https://stackoverflow.com/questions/53526970/search-for-value-in-list-in-python-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!