开发者

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

开发者 https://www.devze.com 2023-02-21 11:23 出处:网络
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\',

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)]


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!

0

精彩评论

暂无评论...
验证码 换一张
取 消