Python3:列表到嵌套字典,使用前12个列表项作为第二级键

时间:2018-09-25 15:20:59

标签: python python-3.x dictionary nested type-conversion

  • bash脚本的subprocess.check_output以字符串形式从MySQL表返回查询。
  • split()给了我一个列表,其中包含从左上角读取的每个表格单元格作为一项,如下所示:
  

list = ['column1_label','column2_label',...,'column1_row1_value',   'column2_row1_value,...,'column1_row2_value','column2_row2_value']

该表有12个静态列。现在,我想使用列表的前12个项目(表中的列标签)作为嵌套字典中的“第二级”键,如下所示:

{'row1': {'column1': 'value', 'column2': 'value', 'column3': 'value', ...}
{'row2': {'column1': 'value', 'column2': 'value', 'column3': 'value', ...}

我的python技能仍然基本。我什至不知道从哪里开始。有一些回答的问题涵盖了列表到嵌套dict转换的列表,但没有一个专门回答这种情况。

4 个答案:

答案 0 :(得分:1)

您可以对enumerate使用字典理解:

L = ['column1_label', 'column2_label', 1, 2, 3, 4, 5, 6]

k, m = 2, 2
res = {f'row{i}': dict(zip(L[:k], row)) for i, row in \
       enumerate(zip(L[k::m], L[k+1::m]), 1)}

结果:

{'row1': {'column1_label': 1, 'column2_label': 2},
 'row2': {'column1_label': 3, 'column2_label': 4},
 'row3': {'column1_label': 5, 'column2_label': 6}}

当然,由于您的输入列表具有非结构化的性质,因此您必须适当地手动修改k, m。但是同样的原理也适用。

答案 1 :(得分:0)

假设此列表称为X,并且需要将第一个12元素设为第二级密钥。 假设您有一个列表Y,其长度为12,其值与这12个键相对应。

假设每一行都对应于它自己的XY,我们可以这样做

outer_dict = {}
for i, row in enumerate(rows): # enumerate gives index along with the row
  X, Y = split(row) # assume this gets X and Y from each row 
  keys = X[:12] # first 12 values of X
  inner_dict = {key: value for (key, value) in zip(keys, Y)} # create inner dict
  outer_dict['row{0}'.format(i + 1)] = inner_dict # create new key for outer dict

答案 2 :(得分:0)

此处list包含标签的某些值。

list = ['column1', 'column2', 'column3', 'column4', 'column5', 'column6', 'column7', 'column8', 'column9', 'column10', 'column11', 'column12',
        'column13', 'column14', 'column15', 'column16', 'column17', 'column18' , 'column19']

访问列表的前12个元素

 list_12 = list[:12]

您有一本带有第一级键的字典。

dictionary = {'row1':{}}

通过list_12循环创建第二级密钥

for i in list_12:
    dictionary['row1'][i] = 'value'

print(dictionary)

输出

  

{'row1':{'column1':'value','column2':'value','column3':'value',   'column4':'值','column5':'值','column6':'值','column7':   'value','column8':'value','column9':'value','column10':'value',   'column11':'value','column12':'value'}}

答案 3 :(得分:0)

我的解决方案受到PraveenRB的回答的启发:

# Start bash script getSOAPconfig, with 2 arguments: 1 = host, 2 = db to query
# argv[1] is the first argument given when calling soap.generator.py

egon_external = str(subprocess.check_output(["./getSOAPconfig", sys.argv[1], backends[db]]).decode()).split()

# extract the labels of the column
col_labels = egon_external[:12]

# create a dictionary that uses the col_labels as key
def make_dict(i):
    start = 12*i+12
    i = 0
    result_dict = dict()
    for row in egon_external[start:start+12]:         # for every 12 items
        if i == 12: i = 0                             # in the egon_external list
        result_dict.update({col_labels[i]: row})      # use col_labels as key
        i += 1                                        # then start at col_labels[0] again.
    return result_dict

row_count = int((len(egon_external)-12)/12)
dict_list = []

# Make a list of dictionaries
for i in range(row_count):
    dict_list.append(make_dict(i))

# Now I can call each row by giving the row number (starting from 0) as list index
# of dict_list and the column name as 2nd level key, like so.
print(dict_list[-1]['ext_id'])

谢谢@all!