【问题标题】:get key from value python从值python获取键
【发布时间】:2014-07-22 15:36:11
【问题描述】:

我有一个 txt 文件,里面有很多这样的行

369136986 cms_trk_dcs_05:CAEN/CMS_TRACKER_SY1527_8/branchController05/easyCrate1/easyBoard03/channel002

两列,第一列是数字,第二列是属性用/分隔的行,两列用空格分隔。

我做了一本字典,其中 key1 是
出现在行中的第一个数字 (369136986),该键作为另一个字典的值,其中键是 cmstrktrackersybranchcrateboard、@987654329 @ 并且每个键 key 都有一个值 cms_trk_dcs_05:CAENCMS_TRACKER_SY1527_8branchController05easyCrate1easyBoard03channel002,所以如果你问cmstrk(key2)@987654337 @(key1) 返回cms_trk_dcs_05(值)。

如何通过给出值来获取密钥?我的意思是,如果我给出值 CMS_TRACKER_SY1527_8,我需要知道 key1 对应于哪个(程序应该返回 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'

那么我怎样才能得到第一把钥匙呢?

【问题讨论】:

  • 是否将 if 语句更改为 if k in m.values(): 得到你想要的?
  • 你能举一个输入字典的例子,它更容易剪切和粘贴吗?这里的问题是 m 有时是一个字典,不能用作另一个字典的键。
  • 您也可以将zip(HVInfoDict.keys(),HVInfoDict.values()) 替换为HVInfoDict.items(),因为它会返回相同的元组列表。
  • 大卫罗宾逊,是的,我必须查看 m.values,谢谢!
  • jonrsharpe,感谢 David Robinson 和 Jhon Rudell,现在它已解决,感谢您的评论。 pavel_form 也谢谢你

标签: python parsing dictionary key


【解决方案1】:

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!

【讨论】:

  • Jhon Rudell 你说得对,我找错地方了,非常感谢你的回答,我的脚本现在可以工作了!
  • @celonilanaparticle 太棒了!很高兴我能帮上忙!
猜你喜欢
  • 2020-01-11
  • 1970-01-01
  • 2013-08-27
  • 2018-02-04
  • 2020-07-22
  • 2021-11-09
  • 1970-01-01
  • 2013-07-02
  • 1970-01-01
相关资源
最近更新 更多