如何使用Python将多个列表合并成字典?

时间:2020-10-14 12:14:05

标签: python json

我正在使用Python将txt文件转换为JSON。但是,当我迭代txt中的行时,结果在那里包含多个列表,并且我无法使用zip()函数将列表合并成字典。谁能帮我解决这个问题?我已经在这里呆了几个小时。谢谢。

 with open(path, encoding='utf-8-sig') as f:
    seq = re.compile("[|]")
    for line_num, line in enumerate(f.readlines()):
        result = seq.split(line.strip("\n"))
        print(result)

这是输出:

['Delivery', 'Customer Name', 'Shipment Priority', 'Creation Date', 'Customer Number', 'Batch Name', 'Release Date']
['69328624', 'Zhidi Feng', 'Standard Priority', '13-OCT-20', '432579', '19657423', '13-OCT-20 00:01:07']
['69328677', 'Zhengguo Huang', 'Standard Priority', '13-OCT-20', '429085', '19657425', '13-OCT-20 00:01:34']

3 个答案:

答案 0 :(得分:2)

类似的东西吗?

>>> lists = [["12", "Abc", "def"], ["34", "Ghi", "jkl"]]
>>> fields = ["id", "lastname", "firstname"]
>>> dicts = []
>>> for l in lists:
...     d = {}
...     for i in range(3):
...             d[fields[i]] = l[i]
...     dicts.append(d)
>>> dicts
[{'id': '12', 'lastname': 'Abc', 'firstname': 'def'}, 
{'id': '34', 'lastname': 'Ghi', 'firstname': 'jkl'}]

编辑:包含在您现有的代码中:

    dicts = []
    for line_num, line in enumerate(f.readlines()):
        result = seq.split(line.strip("\n"))
        if line_num = 0:
            keys = result
        else:
            d = {}
            for i, key in enumerate(keys):
                d[key] = result[i]
            dicts.append(d)

(由于没有您正在使用的文件,因此我没有对此进行测试)

答案 1 :(得分:1)

您可以使用zip制作这样的字典。 (我将键和值分成两个列表。)

with open(path, encoding='utf-8-sig') as f:
    seq = re.compile("[|]")
    lines = f.readlines()
    keys = lines[0] # stting keys
    dict_list = []
    for line_num, line in enumerate(lines[1:]):
        result = seq.split(line.strip("\n"))
        dict_list.append(dict(zip(keys, result))) # making a dict and append it to list


答案 2 :(得分:0)

>>> total
[['Delivery', 'Customer Name', 'Shipment Priority', 'Creation Date', 'Customer Number', 'Batch Name', 'Release Date'], ['69328624', 'Zhidi Feng', 'Standard Priority', '13-OCT-20', '432579', '19657423', '13-OCT-20 00:01:07'], ['69328677', 'Zhengguo Huang', 'Standard Priority', '13-OCT-20', '429085', '19657425', '13-OCT-20 00:01:34']]
>>> keys = total[0]
>>> 
>>> values = total[1:]
>>> wanted = [ dict(zip(keys, value)) for value in values]
>>> wanted
[{'Delivery': '69328624', 'Customer Name': 'Zhidi Feng', 'Shipment Priority': 'Standard Priority', 'Creation Date': '13-OCT-20', 'Customer Number': '432579', 'Batch Name': '19657423', 'Release Date': '13-OCT-20 00:01:07'}, {'Delivery': '69328677', 'Customer Name': 'Zhengguo Huang', 'Shipment Priority': 'Standard Priority', 'Creation Date': '13-OCT-20', 'Customer Number': '429085', 'Batch Name': '19657425', 'Release Date': '13-OCT-20 00:01:34'}]