user10332687
user10332687

Reputation:

Using a filter/map to condense a for loop

Is there a way to write a filter or map do the the following as a one-liner?

formatted_data = []
for hit in res['hits']['hits'][:201]:
    src = hit['_source']
    formatted_data.append({
        'path': src['path'],
        'size': src['size'],
        'last_modified': dateutil.parser.parse(src['last_modified']).date()
    })

Upvotes: 0

Views: 48

Answers (2)

Albin Paul
Albin Paul

Reputation: 3419

This is a oneliner using map and lamda function that i came up . But its less readable

formatted_data=map(lambda x : {'path':x['_source']['path'],'size': x["_source"]['size'],'last_modified': dateutil.parser.parse(x["_source"]['last_modified']).date() },res['hits']['hits'][:201])

I think if you really want to use map write another function and make it more readable like

def returndict(x):
        return {
                'path':x['_source']['path'],
                'size': x['_source']['size'],
                'last_modified': dateutil.parser.parse(x['_source']['last_modified']).date() 
        }
print(map(returndict,res['hits']['hits'][:201])])

I would like to quote zen of python

Beautiful is better than ugly. Explicit is better than implicit.

Simple is better than complex. Complex is better than complicated.

Flat is better than nested. Sparse is better than dense.

Readability counts.

Upvotes: 1

lenik
lenik

Reputation: 23538

It's going to be quite ugly:

formatted_data = [ {
        'path': hit['_source']['path'],
        'size': hit['_source']['size'],
        'last_modified': dateutil.parser.parse(hit['_source']['last_modified']).date()
} for hit in res['hits']['hits'][:201] ]

but you may stretch it into a single line if you like.

Upvotes: 2

Related Questions