如何从python中的字典中的给定名称获取密钥 [英] How to get the key from a given name in dictionary in python
问题描述
anime_dict
的变量,其中包含一个对象列表的字典,如下所示。
{'JI2212':(' (年,1992年),('年份',3)]),'EH389J':(火影忍者',[('年',1994)读者',3424322)]),PPP67(水果篮,[('年',1999),('评级',5),('读者',434232) ])}
所以dict的关键是第一部分(Inu Yasha的'JI2212'),第二部分是名字,最后一部分包含一个部分。
我想创建2个函数,第一个从给定的名称获取密钥,第二个从给定的名称获取元素。
这些函数将是...
get_key(name)
和get_parts(name)
br>例如
>>> get_key('Fruits Basket')
'PPP67'
和
>>> get_parts('Inu Yasha')
[('year',1992),('rating',3)]
在技术上这是可能,但我不建议你这样做,因为它将不高效,map是设计用来获取一个值的值。在你的情况下,我认为更好地从以下重新获取你的数据:
{'JI2212':('Inu Yasha',[ 'year',1992),('rating',3)])}
to
{'Inu Yasha':('JI2212',[('year',1992),('rating',3)])
那么很容易实现你的目标。
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.
这篇关于如何从python中的字典中的给定名称获取密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!