Daniel Dow
Daniel Dow

Reputation: 517

Looking for a Python dict comprehension from a loop I wrote

I'm new to Python and trying to write a dictionary comprehension from this for loop:

    results = []
    for line in self.data:
        if value in line:
            item = dict(zip(self.keys, line))
            results.append(item)
        continue
    return results

self.keys is a list self.data is a list of lists of values that belong to those keys. Basically, I have a list of values from the top of a tab-delimited text file (the keys) and then a bunch of rows of for the values of the actual items represented in the file:

[scene, take, camera]
[12, 1, A]
[12, 1, B]
[12, 2, A]
[12, 2, B]

etc...

I want,

{scene:12, take:1, camera:A}

The code I have works, but I'm trying to learn so I'm wondering if someone can teach me how to write that as a comprehension.

Any help would be appreciated!

Thanks,

Dan

Upvotes: 0

Views: 233

Answers (3)

matsjoyce
matsjoyce

Reputation: 5844

First of all, you can simplify your code to:

results = []
for line in self.data:
    if value in line:
        item = dict(zip(self.keys, line))
        results.append(item)
return results

This shows your looping is for line in self.data, your value is dict(zip(self.keys, line)) and your condition is value in line, so you put the value, then loop, then conditional - `[value loop conditional]. Your list comprehension becomes:

result = [dict(zip(self.keys, line)) for line in self.data if value in line]
return result

You can eliminate result, to give you:

return [dict(zip(self.keys, line)) for line in self.data if value in line]

However, as DSM points out, you can simply do:

import csv
with open("...") as f:
    return list(csv.DictReader(f, fieldnames=next(f).strip().split(), dialect="excel_tab"))

Upvotes: 1

agamagarwal
agamagarwal

Reputation: 988

Based on what I can understand from the question, this should work

result=[dict(zip(self.keys, line)) for line in self.data if value in line]

Upvotes: 1

TigerhawkT3
TigerhawkT3

Reputation: 49318

Try this:

return [dict(zip(self.keys, line)) for line in self.data if value in line]

This would actually be a list comprehension, since we're building a list.

Upvotes: 2

Related Questions