将嵌套列表转换为字典

时间:2020-09-08 21:30:38

标签: python dictionary nested-lists

我要转换为字典的嵌套列表如下:

my_dict = {}
book_ratings = [['Ben'],['5', '0', '1', '4'], ['Sally'],['0', '7', '3', '3']]

我正在尝试将名称["Ben"], ["Sally"]作为键,并将等级["5","0","1","4"], ["0","7","3","3"]作为值。

希望输出:

 {"Ben": ["5", "0", "1", "4"], "Sally": ["0", "7", "3", "3"]}

6 个答案:

答案 0 :(得分:6)

简单的字典补偿:

>>> it = iter(book_ratings)
>>> {k: next(it) for k, in it}
{'Ben': ['5', '0', '1', '4'], 'Sally': ['0', '7', '3', '3']}

使用接受的答案的解决方案(f1f2和我的(f3)进行基准测试,三回合,数字是几秒钟的时间,因此lower = faster:

2.31 f1
2.08 f2
1.39 f3

2.30 f1
2.03 f2
1.34 f3

2.30 f1
2.08 f2
1.31 f3

基准代码:

from timeit import repeat

book_ratings = []
for i in range(1000):
    book_ratings += [["Ben" + str(i)],["5", "0", "1", "4"]]    

def f1():
    i = iter(book_ratings)
    return dict((a[0], b) for a, b in zip(i, i))

def f2():
    return dict((a, b) for (a,), b in zip(book_ratings[::2], book_ratings[1::2]))

def f3():
    it = iter(book_ratings)
    return {k: next(it) for k, in it}

for _ in range(3):
    for f in f1, f2, f3:
        t = min(repeat(f, number=10000))
        print('%.2f' % t, f.__name__)
    print()

答案 1 :(得分:2)

如果book_ratings的结构是名称,列表,名称,列表...,则可以使用此示例来构造字典:

book_ratings = [["Ben"],["5", "0", "1", "4"], ["Sally"],["0", "7", "3", "3"]]

i = iter(book_ratings)
my_dict = dict((a[0], b) for a, b in zip(i, i))

print(my_dict)

打印:

{'Ben': ['5', '0', '1', '4'], 'Sally': ['0', '7', '3', '3']}

或者:

my_dict = dict((a, b) for (a,), b in zip(book_ratings[::2], book_ratings[1::2]))

答案 2 :(得分:2)

您可以使用iter和一些zip魔术来获取其他所有键。但是由于您的键在列表中,并且您只想要它们中的单个值,因此需要使用dict理解:

book_ratings = [["Ben"],["5", "0", "1", "4"], ["Sally"],["0", "7", "3", "3"]]
my_dict = {k[0]: v for k, v in zip(*([iter(book_ratings)]*2))}

{'Ben': ['5', '0', '1', '4'], 'Sally': ['0', '7', '3', '3']}

答案 3 :(得分:1)

您可以使用dict理解来做到这一点,而无需定义一个空dict:

book_ratings = [["Ben"],["5", "0", "1", "4"], ["Sally"],["0", "7", "3", "3"]]
new_dict = {book_ratings[i][0]:book_ratings[i+1] for i in range(0,len(book_ratings),2)}
new_dict

输出:

{'Ben': ['5', '0', '1', '4'], 'Sally': ['0', '7', '3', '3']}

答案 4 :(得分:0)

也许是这样的:

my_dict = {}
book_ratings = [['Ben'],['5', '0', '1', '4'], ['Sally'],['0', '7', '3', '3']]

i=0
while i<len(book_ratings):
  if not book_ratings[i][0].isnumeric():
    my_dict[book_ratings[i][0]] = book_ratings[i+1]
    i+=2
  else:
    i+=1

print(my_dict)

输出:

{'Ben': ['5', '0', '1', '4'], 'Sally': ['0', '7', '3', '3']}

答案 5 :(得分:0)

另一种解决方案,对于初学者来说可能更简单

my_dict =  {}
book_ratings = [['Ben'],[5, 0, 1, 4], ['Sally'],[0, 7, 3, 3]]
for i, book in enumerate(book_ratings):
    if (i==0) or (i%2==0):
        try:
            my_dict[book[0]] = book_ratings[i+1]
        except:
            pass
        
print(my_dict)

打印

  {'Ben': [5, 0, 1, 4], 'Sally': [0, 7, 3, 3]}