简体   繁体   中英

ConfigParser Get Key on given Value

Using ConfigParser I can read value of key easily as shown in the example below-

#config.cfg

[NODE]
192.168.31.22 = node22
192.168.31.23 = node23
192.168.31.26 = node26

#PYTHON CODE
config = ConfigParser.RawConfigParser()
config.readfp(open("config.cfg"))
print config.get("NODE", "192.168.31.22")
>>>node22

Sometime it is required that I read "key" based on given value. Is there any built-in function to get KEY based on the given VALUE or any workaround for this ?

print config.FUNCTIONXYZ("NODE", "node22")
>>>192.168.31.22

Thank you.

No, there is no direct way. Internally, ConfigParser reads the configuration file into a nested dictionary, and in each sections keys are mapped to values, not the other way around. Frankly, I'm not sure why you want this, but I suspect it's not a common request :)

Implementing your own is very easy, however:

# items in section 'NODE': key, value pairs
for key, value in config.items('NODE'):
  if value == WHAT_I_NEED:
    print key

If you need many such lookups on a large configuration, consider placing items into a dict first.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM