0

I have run my brain in circles trying to figure out this problem but no luck.

Basically, I have two containers: one is a list of tuples, the other is a dictionary where each value is a list, and each list contains a series of tuples.

company_list = [('BANK OF AMERICA, NATIONAL ASSOCIATION', 287),
                ('TRANSUNION INTERMEDIATE HOLDINGS, INC.', 982),
                ('Experian Information Solutions Inc.', 929),
                ('EQUIFAX, INC.', 716),
                ('WELLS FARGO & COMPANY', 268)]

company_dict = {'2012': [('BANK OF AMERICA, NATIONAL ASSOCIATION', 784),
                         ('WELLS FARGO & COMPANY', 495),
                         ('JPMORGAN CHASE & CO.', 394),
                         ('CITIBANK, N.A.', 293),
                         ('CAPITAL ONE FINANCIAL CORPORATION', 212),
                         ('OCWEN LOAN SERVICING LLC', 196)],
                '2013': [('BANK OF AMERICA, NATIONAL ASSOCIATION', 882),
                         ('WELLS FARGO & COMPANY', 532),
                         ('JPMORGAN CHASE & CO.', 435),
                         ('CITIBANK, N.A.', 310),
                         ('OCWEN LOAN SERVICING LLC', 255),
                         ('Experian Information Solutions Inc.', 235),
                         ('EQUIFAX, INC.', 221),
                         ('TRANSUNION INTERMEDIATE HOLDINGS, INC.', 196)]}

I'm trying to write a code that will return a list of the numeric values for any given company that appears in both 2012 and 2013.

A for loop seems to work, but I need to write this five times and I would much, much rather use a list comprehension to do it.

Here is the for loop:

y1 = []
for k, v in company_dict.items():
    for tpl in v:
        if tpl[0] == company_list[0][0]:
           y1.append(tpl[1])

The output:

y1: [784, 882]

The loop is using cross-referencing each company name in company_dict (tpl[0]) to see if any of them match the first company name in company_list (company_list[0][0]), which is Bank of America in this example.

I try to reproduce this code as a list comprehension and it fails:

y1 = [tpl[1] for tpl in v for k,v in company_dict.items() if tpl[0] == company_list[0][0]]

In this case I get the following output:

y1: [882, 882]

I'm not sure why the code is doing this, although admittedly I am not a huge expert with list comprehensions. I don't know why I'm not getting the same results for the comprehension as with the for loop, is there any obvious error in construction that I'm missing?

njrob
  • 75
  • 8
  • 1
    You had it a bit turned around. It should be `[tpl[1] for k,v in company_dict.items() for tpl in v if tpl[0] == company_list[0][0]]` - a comprehension just turns your code sideways. – TigerhawkT3 Jan 18 '19 at 04:54
  • Works perfectly. Thanks! – njrob Jan 18 '19 at 04:57

0 Answers0