write dictionary of lists to a tab delimited file in python, with dictionary key values as columns without Pandas

Ahmad Faheem :

the dictionary I am using is:

dict={'item': [1,2,3], 'id':['a','b','c'], 'car':['sedan','truck','moped'], 'color': ['r','b','g'], 'speed': [2,4,10]}

I am trying to produce a tab delimited out put as such:

item    id
1       a
2       b
3       c

The code I have written:

with open('file.txt', 'w') as tab_file:
    dict_writer = DictWriter(tab_file, dict.keys(), delimiter = '\t')
    dict_writer.writeheader()
    dict_writer.writerows(dict)

specifically, I am struggling with writing to the file in a column based manner. Meaning, that the dictionary keys populate as the header, and the dictionary values populate vertically underneath the associated header. Also, I do NOT have the luxury of using Pandas

Ruan :

This solution will work for an ambiguous number of items and subitems in the dict:

d = {'item': [1, 2, 3], 'id': [4, 5, 6]}

for i in d:
    print(i + "\t", end="")
    numSubItems = len(d[i])
print()


for level in range(numSubItems):
    for i in d:
        print(str(d[i][level]) + "\t", end="")
    print()



EDIT: To implement this with writing to a text file:

d = {'item': [1, 2, 3], 'id': [4, 5, 6], 'test': [6, 7, 8]}


with open('file.txt', 'w') as f:
    for i in d:
        f.write(i + "\t")
        numSubItems = len(d[i])
    f.write("\n")

    for level in range(numSubItems):
        for i in d:
            f.write(str(d[i][level]) + "\t")
        f.write("\n")

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=297502&siteId=1