How to get the key from a given name in dictionary in python

独自空忆成欢 提交于 2019-12-02 14:30:47

问题


I have a variable called

anime_dict
which contains a dictionary of lists of objects as shown below.
{'JI2212': ('Inu Yasha', [('year', 1992), ('rating', 3)]), 'EH389J': (Naruto', [('year', 1994), ('rating', 4), ('readers', 3424322)]), 'PPP67': ('Fruits Basket', [('Year', 1999), ('rating', 5), ('readers', 434232), ('chap', 40)])}

so the key of the dict is the 1st part ('JI2212' for Inu Yasha), the 2nd part is the name and the last part contains a list of parts.
I want to create 2 functions that would 1st get the key from the given name and 2nd get the parts from the given name.
the functions would be...
get_key(name)
and get_parts(name)


for instance

>>>get_key('Fruits Basket')
'PPP67'
and
>>>get_parts('Inu Yasha')
[('year', 1992), ('rating', 3)]

回答1:


It is possible technically, but i would not recommend you to do that, because it will not be efficient, map is designed to use a key to get a value. In your case i think its better to restuct your data from:

{'JI2212': ('Inu Yasha', [('year', 1992), ('rating', 3)])}

to

{'Inu Yasha': ('JI2212', [('year', 1992), ('rating', 3)])}

then it is very easy to achieve your goal.




回答2:


There's keys and values methods. Use those, do not do it entry-by-entry, it'll be very slow, because search of key by value is linear.




回答3:


You should really have your key's be the anime names, it makes life a lot easier.

For example, now your dictionary is being inserted like:

anime_dict[id] = (name,...)

A better way would be to do:

anime_dict[name] = (id,...)

Unless you have a specific reason have the key's be id, this way is just generally easier to understand and use.




回答4:


If you just want to convert your original dictionary to a new one, you can run the following:

old_dict = {'JI2212': ('Inu Yasha', [('year', 1992), ('rating', 3)]), 'EH389J': ('Naruto', [('year', 1994), ('rating', 4), ('readers', 3424322)]), 'PPP67': ('Fruits Basket', [('Year', 1999), ('rating', 5), ('readers', 434232), ('chap', 40)])}

new_dict = {}
for key in old_dict.keys(): 
    name = old_dict[key][0]
    data = old_dict[key][1:]
    new_dict[name]=(key, data)

Hope it helps!



来源:https://stackoverflow.com/questions/5527285/how-to-get-the-key-from-a-given-name-in-dictionary-in-python

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