Say for an example, I’ve a list like this:
q_list = [('94.vmtest2', 'sgmops', 'Andy Hays', '27/04 00:27:26', 'C', '27/04 00:28:31', 'vmtest1.hep', 'express', '00:00:10', '00:01:04'),
('96.vmtest2', 'sgmops', 'John Dee', '27/04 01:27:26', 'C', '27/04 01:28:33', 'vmtest1.hep', 'short', '00:00:09', '00:01:06'),
('99.vmtest2', 'sgmops', 'Andy Hays', '27/04 07:19:56', 'C', '27/04 07:21:12', 'vmtest1.hep', 'express', '00:00:10', '00:01:14'),
('103.vmtest2', 'sgmops', 'John Dee', '27/04 14:08:00', 'C', '27/04 14:09:16', 'vmtest1.hep', 'express', '00:00:10', '00:01:16'),
('102.vmtest2', 'sgmops', 'John Dee', '27/04 14:02:38', 'C', '27/04 14:10:12', 'vmtest1.hep', 'short', '00:00:10', '00:01:10')]
which is formed from the log files. and then I have a dictionary like this:
q_dict = {'username': 'johndee', 'queue': 'short'}
which is formed from a query string (the user input). What I want is to print [first 8 items of] the only lines from the list match with the value in the dictionary. In this case, I’ll only print these two lines:
96.vmtest2 sgmops John Dee 27/04 01:27:26 C 27/04 01:28:33 vmtest1.hep short
102.vmtest2 sgmops John Dee 27/04 14:02:38 C 27/04 14:10:12 vmtest1.hep short
In fact it doesn’t have to be a dictionary at all; the user input (command-line argument) is like this:
'formatDate(%m/%d) == 4/27 && username == John Dee && queue == short'
and I’m creating the dictionary out of that. Any idea how can I do that? Thanks in advance for any help. Cheers!!
The most common approach is to use a list comprehension, for instance to filter by username:
You can also use
filter:You can thus use your
q_dictto filter by user and/or queue easily.As suggested in Space_C0wb0y’s answer, using
namedtuplewould be a good approach, you can map out the fields rather easily:For the sake of the argument, let’s convert the tuples in your list to namedtuples:
And then you can filter dynamically based on the query params. For instance to get a list of items where all query params match the given fields:
That is assuming the username in
q_dictactually matched the field for username…it doesn’t in your example but you can work around that. Similarly you could create a list of dicts, that’d make working with your list a bit easier:Which would give you a list of dicts like:
Then you can filter similarly:
Personally I think I prefer the dict approach. Whole things rolled up using for loops instead (and one generator expression):