简体   繁体   中英

How do I convert list of tuple of dictionary of list to a csv file?

I have a nested list that looks something like this:

list:

[('CN=GON,OU=App,OU=Groups,DC=com', {'member': [b'CN=user1,OU=Users,DC=com', b'CN=user2,OU=Users,DC=com',]})]

What should I do to convert this to a csv file that looks something like this:

out.file:

user1
user2

with the list you provided:

lst = [('CN=GON,OU=App,OU=Groups,DC=com', {'member': [b'CN=user1,OU=Users,DC=com', b'CN=user2,OU=Users,DC=com']})]

csvOutput = []

for user in lst[0][1]['member']:
    strUser = user.decode("utf-8").split(',')
    newRow = []

Now, if you want only the the 'CN' as an output:

    newRow.append(strUser[0].split("=")[1])

    csvOutput.append(newRow)

Or if you want all the data:

    for data in strUser:
        newRow.append(data.split("=")[1])

    csvOutput.append(newRow)

And finally, to write this in a csv file:

import csv

with open('yourFile.csv', 'w') as f:
    write = csv.writer(f)
    write.writerows(csvOutput)

Note that the last part can be done with pandas as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM