从python值获取密钥
我有一个txt文件,里面有很多这样的行从python值获取密钥,python,parsing,dictionary,key,Python,Parsing,Dictionary,Key,我有一个txt文件,里面有很多这样的行 369136986 cms_trk_dcs_05:CAEN/CMS_TRACKER_SY1527_8/branchController05/easyCrate1/easyBoard03/channel002 两列,其中第一列有数字,第二列是一行,属性用/分隔,两列都用空格分隔 我做了一本字典,其中键1是 行中出现的第一个数字(369136986),此键作为另一个字典的值,其中键为cmstrk,trackersy,分支,板条箱,板,通道,这些键中的每个键都
369136986 cms_trk_dcs_05:CAEN/CMS_TRACKER_SY1527_8/branchController05/easyCrate1/easyBoard03/channel002
两列,其中第一列有数字,第二列是一行,属性用/
分隔,两列都用空格分隔
我做了一本字典,其中键1是行中出现的第一个数字(
369136986
),此键作为另一个字典的值,其中键为cmstrk
,trackersy
,分支
,板条箱
,板
,通道
,这些键中的每个键都作为值cms\u trk\u dcs\u 05:CAEN
,CMS\u TRACKER\u SY1527\u 8
,branchcontroller 05
,easyCrate1
,easyBoard03
,channel002
,因此,如果您为369136986
(key 1)询问cmstrk
(key 2),它将返回CMS\u trk\u dcs\u 05
(值)
如何通过给出值来获取密钥?我的意思是,如果我给出值CMS\u TRACKER\u SY1527\u 8
,我需要知道哪个键对应(程序应该返回369136986
)
这就是我所尝试的:
input3=raw_input("Write the property(s) which modules connected you want to know, separated by a single space \n > ")
input_list3=input3.split(' ')
for k in input_list3:
print "%r" % k
txt.write("\t\n The modules with property %r are:\n" % k)
for l,m in zip(HVInfoDict.keys(),HVInfoDict.values()):
if k == HVInfoDict[l][m]:
print l
但它又回来了
TypeError: unhashable type: 'dict'
那么我怎样才能得到第一个键呢?m是在HVInfoDict[l]中检索到的整个字典。。您需要像这样查看m中的值
HVInfoDict = {
369136986: {
'cmstrk': 'cms_trk_dcs_05:CAEN',
'trackersy': 'CMS_TRACKER_SY1527_8',
'branch': 'branchController05',
'crate': 'easyCrate1',
'board': 'easyBoard03',
'channel': 'channel002'
}
}
input3 = raw_input("Write the property(s) which modules connected you want to know, separated by a single space \n > ")
input_list3 = input3.split(' ')
for k in input_list3:
print "%r" % k
txt.write("\t\n The modules with property %r are:\n" % k)
for l,m in HVInfoDict.items():
if k in m.values():
print l
else:
print("Does not exist!")
输出:
Write the property(s) which modules connected you want to know, separated by a single space
> branchController05 CMS_TRACKER_SY1527_8 channel002 abcdefg
'branchController05'
369136986
'CMS_TRACKER_SY1527_8'
369136986
'channel002'
369136986
'abcdefg'
Does not exist!
将if语句更改为
if k in m.values():
是否满足了您的需要?能否举一个更易于剪切和粘贴的输入字典示例?这里的问题是,m
有时是一个字典,不能用作另一个字典的键。另外,你可以用HVInfoDict.keys(),HVInfoDict.values())
替换zip(HVInfoDict.key(),HVInfoDict.values())
,因为它将返回相同的元组列表。David Robinson,是的,我必须在m.values中查找,谢谢!jonrsharpe,感谢David Robinson和Jhon Rudell,现在问题已经解决了,谢谢你的评论。pavel_表单感谢你tooJhon Rudell你是对的我找错地方了,非常感谢你的回答,我的脚本现在可以工作了@塞罗尼亚:太棒了!很高兴我能帮忙!