这是我的词典
finance={
'sno' : 'None',
'fin_ticker' : 'what',
'marketcap' : ['what','how much'],
'e_value' : ['what', 'how much'],
'ret_on_assets' : ['how much', 'what'],
'tot_cash' : 'what',
'op_cash' :'what',
'lev_free_cf' :'what',
'tot_debt' : 'what',
'curr_ratio' : ['what', 'how much'],
'gross_profit' :['what', 'how much'],
'prof_margin' :['what', 'how much'],
'last_trade' : ['what', 'how much'],
'trade_time' : ['what', 'when'],
'prev_close' : ['what', 'how much'],
}
我需要获取给定值的键...例如,当我给出一个值为' what'它显示有关该值的所有键,如下所示
fin_ticker
marketcap
e_value
ret_on_assets
tot_cash
op_cash
lev_free_cf
tot_debt
curr_ratio
gross_profit etc...
答案 0 :(得分:1)
您可以使用函数返回包含预期键的生成器:
def key_finder(d,val):
for key in d :
value=finance[key]
if value==val:
yield key
elif isinstance(value,list) and val in value:
yield key
演示:
>>> list(key_finder(finance,'what'))
['op_cash', 'prev_close', 'curr_ratio', 'lev_free_cf', 'last_trade', 'marketcap', 'tot_cash', 'ret_on_assets', 'gross_profit', 'trade_time', 'prof_margin', 'fin_ticker', 'e_value', 'tot_debt']
>>> list(key_finder(finance,'how much'))
['prev_close', 'curr_ratio', 'last_trade', 'marketcap', 'ret_on_assets', 'gross_profit', 'prof_margin', 'e_value']
答案 1 :(得分:0)
您应该使用
迭代键for key in finance.keys():
if ( finance[key] == value )
print "key: %s , value: %s" % (key, finance[key])
elif isinstance(finance[key],list) and value in finance[key]:
print "key: %s , value: %s" % (key, finance[key])