gt6989b
gt6989b

Reputation: 4203

Pythonic way to produce a list from nested dictionary

working in Python 2.7, I have a nested dictionary with some quote data, from which I would like to produce a list of successfully constructed quotes. Currently, here is how I do this:

result = []
for nameStr, nameData in dataTbl.iteritems():
    for valueDate, record in nameData.iteritems():
        quote = histRecordToQuote(securitiesDict = securitiesDict,
                                  nameStr        = nameStr,
                                  valueDate      = valueDate,
                                  record         = record)
        if quote:
            result.append(quote)

Is there a more Pythonic way to do this? I have a hunch we can do faster or clearer with a list comprehension. The function histRecordToQuote() returns None when it cannot construct a quote due to a data error. You can suggest a different signature, I'll be happy to rewrite it for clearer/faster code.

Thank you very much.

EDIT

An example of a dictionary structure:

{'IBM':  {'20140215':2.53, '20140216':2.55},
 'MSFT': {'20140213':2.45, '20140216':0.},
 'AMZN': {'20140212':0., '20140214':2.59}}

The parameter securitiesDict is external, it is needed for constructing the Quote class inside histRecordToQuote().

The output from histRecordToQuote() would return None for 0-price records and construct valid Quote from the rest.

Quote('IBM', '20140215', 2.53)
Quote('IBM', '20140216', 2.55)
Quote('MSFT', '20140213', 2.45)
None
Quote('AMZN', '20140214', 2.59)
None

My final output needs to be the list of valid quotes:

[Quote('IBM', '20140215', 2.53),
Quote('IBM', '20140216', 2.55),
Quote('MSFT', '20140213', 2.45),
Quote('AMZN', '20140214', 2.59)]

Upvotes: 3

Views: 107

Answers (1)

Alfe
Alfe

Reputation: 59426

You can achieve the same with a nested comprehension:

[ quote for quote in
    (histRecordToQuote(securitiesDict = securitiesDict,
                       nameStr        = nameStr,
                       valueDate      = valueDate,
                       record         = record)
      for nameStr, nameData in dataTbl.iteritems()
        for valueDate, record in nameData.iteritems())
    if quote ]

Upvotes: 2

Related Questions