使用键定期将平面列表转换为字典

时间:2018-04-12 15:33:46

标签: python python-3.x list dictionary

我有一个包含字符串和列表的列表。我应该告诉你;

list_x = ['a', ['j', '1', 'x'], ['k', '2', 'y'], ['a', '3', 'hj'],
          'd', ['b', '4', 'df'], ['c', '5', 'er'], ['d', '6', 'ty'],
          'g', ['e', '7', 'hj'], ['f', '8', 'bv'], ['g', '9', 'sad'],
          'j', ['h', '10', 'kj'], ['i', '11', 'nbv'], ['c', '12', 'uy'],
          'n', ['d', '13', 'ipoas'], ['e', '14', 'fg'], ['f', '15', 'as'], 
          'r', ['g', '16', 'dsad'], ['h', '17', 'fdgdfg'], ['i', '18', 'retrt'],
          'u', ['j', '19', 'qwe'], ['k', '20', 'ytgf'], ['n', '21', 'asmz']]

我想从这个列表中得到这样的字典;

dict_x = {'a': [['j', '1', 'x'], ['k', '2', 'y'], ['a', '3', 'hj']],
          'd': [['b', '4', 'df'], ['c', '5', 'er'], ['d', '6', 'ty']],
          'g': [['e', '7', 'hj'], ['f', '8', 'bv'], ['g', '9', 'sad']],
          'j': [['h', '10', 'kj'], ['i', '11', 'nbv'], ['c', '12', 'uy']],
          'n': [['d', '13', 'ipoas'], ['e', '14', 'fg'], ['f', '15', 'as']], 
          'r': [['g', '16', 'dsad'], ['h', '17', 'fdgdfg'], ['i', '18', 'retrt']],
          'u': [['j', '19', 'qwe'], ['k', '20', 'ytgf'], ['n', '21', 'asmz']]}

2 个答案:

答案 0 :(得分:3)

这是一个简单循环的直接解决方案:

dict_x = {}
for value in list_x:
    if isinstance(value, str):
        dict_x[value] = current_list = []
    else:
        current_list.append(value)

基本上,如果值是一个字符串,那么新的空列表将被添加到dict中,如果它是一个列表,它将被附加到上一个列表中。

答案 1 :(得分:1)

以下是使用dictionary comprehensiongenerator expression* unpacking相结合的一种方法。

res = {i: j for i, *j in (list_x[i:i + 4] for i in range(0, len(list_x), 4))}

# {'a': [['j', '1', 'x'], ['k', '2', 'y'], ['a', '3', 'hj']],
#  'd': [['b', '4', 'df'], ['c', '5', 'er'], ['d', '6', 'ty']],
#  'g': [['e', '7', 'hj'], ['f', '8', 'bv'], ['g', '9', 'sad']],
#  'j': [['h', '10', 'kj'], ['i', '11', 'nbv'], ['c', '12', 'uy']],
#  'n': [['d', '13', 'ipoas'], ['e', '14', 'fg'], ['f', '15', 'as']],
#  'r': [['g', '16', 'dsad'], ['h', '17', 'fdgdfg'], ['i', '18', 'retrt']],
#  'u': [['j', '19', 'qwe'], ['k', '20', 'ytgf'], ['n', '21', 'asmz']]}

或者,正如@chrisz建议的那样,您可以使用zip

res = {i: j for i, *j in zip(*(list_x[i::4] for i in range(4)))}