简体   繁体   中英

Nested Dictionary Comprehension from a List of Lists in Python 3

edgeList is a list of lists

I have this working but its slower than I want:

for rowIndex, rowVal in enumerate(edgeList):
    for colIndex, colVal in enumerate(rowVal):
        EdgeDict[rowIndex][colIndex] = colVal

Would it be faster using dict comprehension? I tried, but got tangled up in the syntax

A comprehension like this should do it, but I doubt that it is significantly faster. Also, the accessing of values is the same as in the list you have:

edge_dict = {row: dict(enumerate(row_val)) for row, row_val in enumerate(edgeList)}

There is very little point in doing this. You already have a map from coordinate pair to value . Your edgeList is that map:

edgeList[integer_value_for_row][integer_value_for_col]

maps to your values.

You can produce your dictionary with:

{row_index: dict(enumerate(row)) for row_index, row in enumerate(edgeList)}

This maps the result of enumerate() directly to a dictionary; there is no need to nest that loop.

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