On Wed, 21 Sep 2016 04:04 am, Ganesh Pal wrote: > I am on python 2.7 and Linux > > I have the stdout in the below form , I need to write a function to get > hostname for the given id. > > > Example: > >>>> stdout > 'hostname-1 is array with id 1\nhostname-2 is array with id 2\nhostname-3 > is array with id 3\n' > > > def get_hostname(id) > return id > > what's a better option here > > 1. store it in list and grep for id and return > 2. store it in dict as key and value i.e hostname = { 'hostname1': 1} and > return key > 3. any other simple options.
Why don't you write a function for each one, and see which is less work? # Version 1: store the hostname information in a list as strings hostnames = ['hostname-1 is array with id 1', 'hostname-2 is array with id 2', 'hostname-842 is array with id 842'] def get_hostname(id): for line in hostnames: regex = r'(.*) is array with id %d' % id mo = re.match(regex, line) if mo is not None: return mo.group(1) raise ValueError('not found') # Version 2: store the hostname information in a dict {hostname: id} hostnames = {'hostname1': 1, 'hostname2': 2, 'hostname842': 842} def get_hostname(id): for key, value in hostnames.items(): if value == id: return key raise ValueError('not found') # Version 3: use a dict the way dicts are meant to be used hostnames = {1: 'hostname1', 2: 'hostname2', 842: 'hostname842'} def get_hostname(id): return hostnames[id] -- Steve “Cheer up,” they said, “things could be worse.” So I cheered up, and sure enough, things got worse. -- https://mail.python.org/mailman/listinfo/python-list