Animesh Sharma
Animesh Sharma

Reputation: 3386

Nested loops in dictionary comprehension

I have an existing list of dictionaries as follows:

FA = [{u'child': [{u'cdesc': u'Audit'},
                  {u'cdesc': u'Equity Research'},
                  {u'cdesc': u'Finance / Accounts / Tax'},
                  {u'cdesc': u'Investment Banking / M&A'}],
       u'pdesc': u'Finance / Accounts / Investment Banking',
       u'pid': 10007}]

I want to convert it to something like this:

FA = {u'Audit':2,
     u'Equity Research':2,
     u'Finance / Accounts / Tax':2,
     u'Investment Banking / M&A':2,
     u'Finance / Accounts / Investment Banking':2}

I can easily do this using nested loops,the code for which is shown below. Is there any way of doing this using Dictionary comprehension?

a = dict()
for fa in FA:
    a.update({slugify(fa['pdesc']):2})


    for c in fa['child']: 
        a.update({slugify(c['cdesc']):2})

Upvotes: 2

Views: 4468

Answers (3)

Renae Lider
Renae Lider

Reputation: 1024

Dictionary comprehension looks ugly as fu*k here... anyway...

# METHOD 1
FA_dict1 = {d:2 for v in FA[0][u'child'] for d in v.values()}
FA_dict1.update({FA[0][u'pdesc']: 2})


# METHOD 2
from itertools import chain
FA_dict = {d:2 for v in FA[0][u'child'] for d in chain(v.values(), [FA[0][u'pdesc']])}


# METHOD 3
FA_DICT = {d:2 for v in FA[0][u'child'] for d in list(v.values())+[FA[0][u'pdesc']]}

Upvotes: 6

wmoco_6725
wmoco_6725

Reputation: 3169

The comprehension solution is indeed an ugly duckling!

Run this on the above data:

{ k:2 for k in reduce(lambda x,y: x+y, [ [ chld[u'cdesc'] for chld in FA[0]['child'] ], [ FA[0][u'pdesc'] ] ] ) }

{u'Audit': 2,
 u'Equity Research': 2,
 u'Finance / Accounts / Investment Banking': 2,
 u'Finance / Accounts / Tax': 2,
 u'Investment Banking / M&A': 2}

Upvotes: 2

wmoco_6725
wmoco_6725

Reputation: 3169

Would this get you started ?

{ chld[u'cdesc']:2 for chld in FA[0]['child'] }

Which produces (not 100% but close) :

{u'Audit': 2,
 u'Equity Research': 2,
 u'Finance / Accounts / Tax': 2,
 u'Investment Banking / M&A': 2}

Upvotes: 0

Related Questions