简体   繁体   中英

Python create list from a list of lists of dictionaries

I have a list that contains information about ZIP's (their location, size ect) in a list called enclosures .

The list is created with this code:

for item in g.entries:
    enclosure = [l for l in item["links"] if l["rel"] == "enclosure"]
    if(len(enclosure)>0):
        enclosures.append(enclosure)

Every item of the list enclosures has the following format:

>>> enclosures[0]
[{'type': 'application/zip', 'rel': 'enclosure', 'length': '57648', 'href': 'http://www.sec.gov/Archives/edgar/data/37748/000003774810000025/0000037748-10-000025-xbrl.zip'}]

or another example...

>>> enclosures[45]
[{'type': 'application/zip', 'rel': 'enclosure', 'length': '107907', 'href': 'http://www.sec.gov/Archives/edgar/data/1385157/000104746910004400/0001047469-10-004400-xbrl.zip'}]

What i need is to create a list called href which contains every href item from the enclosures list in the same order .

These attempts below have failed.

>>> enclosures[46]["href"]
Traceback (most recent call last):
  File "<pyshell#66>", line 1, in <module>
    enclosures[46]["href"]
TypeError: list indices must be integers, not str

>>> enclosures[46][4]
Traceback (most recent call last):
  File "<pyshell#67>", line 1, in <module>
    enclosures[46][4]
IndexError: list index out of range

EDIT

Dear timgeb

I have this result:

>>> href = [x['href'] for x in enclosures]
Traceback (most recent call last):
  File "<pyshell#75>", line 1, in <module>
    href = [x['href'] for x in enclosures]
  File "<pyshell#75>", line 1, in <listcomp>
    href = [x['href'] for x in enclosures]
TypeError: list indices must be integers, not str
href = [x[0]['href'] for x in enclosures]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM