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

对着背影说爱祢 提交于 2019-12-02 08:28:32

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.

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.

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.

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!

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