Andrew Z wrote: > Hello, > pos = {"CLown":10,"BArbie":20} > I want to return integer (10) for the keyword that starts with "CL" > > > cl_ = [v for k, v in pos.items() if k.startswith('CL')] > cl_pos = cl_[0] > if cl_pos > 0: > > blah.. > > > There are 2 issues with the above: > a. ugly - cl_pos = cl_ [0] . I was thinking something like
There's another issue: what do you want to do if there is more than one match or no match at all? If you are OK with a ValueError in both cases you can rewrite > cl_ = [v for k, v in pos.items() if k.startswith('CL')][0] [match] = (v for k, v in pos.items() if k.startswith("CL")) If the values are orderable you can standardise on the minimum or maximum match = min(v for k, v in pos.items() if k.startswith("CL")) or if you always want an arbitrary match you can pick the first one explicitly: match = next(v for k, v in pos.items() if k.startswith("CL")) This will raise a StopIteration if there are no matches. > but that is too much for the eyes - in 2 weeks i'll rewrite this into > something i can understand without banging against the desk. > So what can be a better approach here ? > > > b. in "cl_pos > 0:, cl_pos apparently is still a list. Though the run in a > python console has no issues and report cl_pos as int. > > > Appreciate. -- https://mail.python.org/mailman/listinfo/python-list