简体   繁体   中英

How can I create a dictionary from a list of lists using the first value of each list as the key

I would like my lists to go from this:

(data1, 2, 3, 4, 5), (data2, 2, 3, 4, 5)

To this:

(data1: 2, 3, 4, 5), (data2: 2, 3, 4, 5)

Here is the code I have tried so far.

from openpyxl import *
from collections import defaultdict

wb = load_workbook('Crossed.xlsx')
crossed_set = {0: (str(row[1].value), row[0].value,
        row[2].value, row[3].value, row[4].value, row[5].value,
        row[6].value, row[7].value, row[8].value,
        row[9].value, row[10].value) for row in wb.worksheets[0].iter_rows(min_row=3, max_row=466, max_col=11)}

crossed_dict = defaultdict(list)
for key in sorted(crossed_set):
        crossed_dict[crossed_set[key][0]].extend(crossed_set[key][1:])

But after adding the "0:" to attempt to turn it into a dictionary, it only creates a dictionary of one of the unordered rows at random like this:

(data, data, data, data, data)

How can I write this so that it returns all of the data instead of stopping at one? Please go easy. I'm new to coding and to Stack Overflow.

This will work:

data = [[1, 2, 3, 4], [5, 6, 7, 8], [6]]
out = {item[0] : item[1:] for item in data}
# {1: [2, 3, 4], 5: [6, 7, 8], 6: []}

Notice that slicing a list has the great property of allowing us to "index" out of bounds: the list [6] has no item at index 1, but when we do [6][1:] there is no error, it just returns an empty list. As a result, this will work for your list of lists assuming the length of each list is at least 1. If that might not be the case, we can use:

data = [[1, 2, 3, 4], [5, 6, 7, 8], [6], []]
out = {item[0] : item[1:] for item in data if len(item) > 0}
# {1: [2, 3, 4], 5: [6, 7, 8], 6: []}

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