晓天蔡
晓天蔡

Reputation: 25

How to merge the multiple lists into a dict with Python?

I'm using Python to translate a txt file into JSON. However, when I was iterating the lines from txt, the result is containing multiple lists there, and I failed to merge the list into a dict with the function zip(). Can anyone help me figure it out? I've been stuck here for a couple of hours. Thanks.

 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)

This is the output:

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

Upvotes: 1

Views: 704

Answers (3)

Aref Sayareh
Aref Sayareh

Reputation: 70

you can use zip for making a dictionary like this. (I separate keys and values in two lists.)

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


Upvotes: 1

ky_aaaa
ky_aaaa

Reputation: 320

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


Upvotes: 0

MarcMush
MarcMush

Reputation: 1488

Something like that ?

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

Edit: included in your existing code:

    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)

(I didn't test this since I don't have the file you're using)

Upvotes: 2

Related Questions