Home > other >  Python for loop to read a JSON file
Python for loop to read a JSON file

Time:11-18

I am trying to understand a Python for loop that is implemented as below

samples= [(objectinstance.get('sample', record['token'])['timestamp'], record) 
            for record in objectinstance.scene]

'scene' is a JSON file with list of dictionaries and each dictionary entry refers through values of the token to another JSON file called 'sample' containing 'timestamp' key among other keys.

Although I can roughly understand at a high level, I am not able to decipher how the 'record' is being used here as the output of object's get method. I am thinking this is some sort of list comprehension, but not sure. Can you help understand this and also point me any reference to understand this better? thank you

CodePudding user response:

in non comprehension form it is as below

samples = []
for record in objectinstance.scene:
    data = (
              objectinstance.get('sample', record['token'])['timestamp'],
              record
           )
    samples.append(data)

objectinstance.get('sample', record['token']) this looks like a method, which took two arguments and return a json/dictionary

{<key1>:<value1>, ... ,'timestmap':<somedata>, ...<keyn>:<valuen>}

and you are saving record with the timestamp value of this call.

it this objectinstance.get can be seen as

class Tmp:
    def __init__(self):
        self.scene = [{'token': 'a'}, {'token':'b'}, {'token':'c'}] 
    def get(self, arg1, arg2):
         # calculation
         
         return result 
     
objectinstance = Tmp()

samples =[]

for record in objectinstance.scene:
    object_instance_data = objectinstance.get('sample', record['token'])
    data = object_instance_data['timestamp']
    samples.append(data)

so as you can see, there is method in the object class name get, which take 2 arguments, and use them calculation to provide you result in dict/json which as timestamp as key value

CodePudding user response:

Yes, you are right, it is a list comprehension. Schematically, it is something like this:

samples = [(timestamp, item) for item in list_of_dicts]

The result will be a list of touples, where (objectinstance.get('sample', record['token'])['timestamp'] is the first entry and record is the second.

Moreover, objectinstance.get('key', default) gets 'key' from a dict, if not present returns the default value, cf. documentation at python.org. The result of the get method seems to be a dict as well, from which the value of key ['timestamp'] is retrieved.

  • Related