Convert flat list to dictionary with keys at regular intervals

I have a list containing a string and lists. I should show you;

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']]

And I want a dict from this list like this;

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']]}

Here's a straightforward solution with a simple loop:

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

Basically, if the value is a string then a new empty list is added to the dict, and if it's a list, it's appended to the previous list.


Here is one way using a dictionary comprehension and a generator expression combined with * 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']]}

Alternatively, as @chrisz suggests, you can use zip :

res = {i: j for i, *j in zip(*(list_x[i::4] for i in range(4)))}
链接地址: http://www.djcxy.com/p/53572.html

上一篇: Python列表(元组)中每个元素有多少个字节?

下一篇: 定期将按键转换为字典