[Tutor] How to get the element from a list
Mats Wichmann
mats at wichmann.us
Wed Nov 13 18:06:39 EST 2019
On 11/13/19 1:22 PM, Eggo why wrote:
> Hi All,
> I have a list like this "line = [{'logname; : 'c:/tmp/alert', 'creationTime': 1573664115985},{'logname; : 'c:/tmp/audit', 'creationTime': 1573664115985}]" and I would like to retrieve the "logname" from it. What is the easiest way to do so?
>
> Gary
let me take a wild guess: you're processing some json files?
presuming what you're looking for is to extract *each* logname value,
you can use a list comprehension. You're going to loop over the elements
of the list, each of which is a dictionary, and index into each element
to pick out the value of the 'logname' key. At the risk of "solving a
homework problem" (which I hope this is not), that could look like this:
lognames = [ d['logname'] for d in line ]
if there's a chance not all of the elements (dictionaries) have
'logname' entries, then you need to get a little more sophisticated, or
it will fail with an exception.
More information about the Tutor
mailing list