1

I have a list that looks like this:

hello = [(('case', 'iphone'), 91524), (('adapter', 'iphone'), 12233), (('battery', 'smartphone'), 88884)]

And I am simply trying to write it to a csv file, looking like this:

keyword 1           keyword 2          frequency
case                iphone             91524
adapter             iphone             12233
battery             smartphone         88884

I can't figure my way around it. I couldn't transform the list into a DataFrame, either. I tried to apply some code suggested here Writing a Python list of lists to a csv file without any success.

jezrael
  • 629,482
  • 62
  • 918
  • 895
Notna
  • 401
  • 1
  • 4
  • 15

4 Answers4

4

Pandas is convenient for this:

import pandas as pd

hello = [(('case', 'iphone'), 91524), (('adapter', 'iphone'), 12233), (('battery', 'smartphone'), 88884)]

df = pd.DataFrame([[i[0][0], i[0][1], i[1]] for i in hello],
                  columns=['keyword 1', 'keyword 2', 'frequency'])

#   keyword 1   keyword 2  frequency
# 0      case      iphone      91524
# 1   adapter      iphone      12233
# 2   battery  smartphone      88884

df.to_csv('file.csv', index=False)
jpp
  • 134,728
  • 29
  • 196
  • 240
4

If in pandas

s=pd.Series(dict(hello)).reset_index()
s.columns=['keyword 1', 'keyword 2', 'frequency']
s
Out[1012]: 
  keyword 1   keyword 2  frequency
0   adapter      iphone      12233
1   battery  smartphone      88884
2      case      iphone      91524
BENY
  • 258,262
  • 17
  • 121
  • 165
2

You can use unpacking:

import csv
hello = [(('case', 'iphone'), 91524), (('adapter', 'iphone'), 12233), (('battery', 'smartphone'), 88884)]
with open('filename.csv', 'w') as f:
   write = csv.writer(f)
   write.writerows([['keyword 1', 'keyword 2', 'frequency']]+[[a, b, c] for [a, b], c in hello])
Ajax1234
  • 58,711
  • 7
  • 46
  • 83
1

If you're OK with using pandas, you can do the following:

import pandas as pd
hello = [(('case', 'iphone'), 91524), (('adapter', 'iphone'), 12233), (('battery', 'smartphone'), 88884)]

df=pd.DataFrame({'keyword1':[i[0][0] for i in hello], 'keyword2':[i[0][1] for i in hello], 'frequency':[i[1] for i in hello]})

df[['keyword1', 'keyword2', 'frequency']].to_csv('test.csv')
sacuL
  • 42,057
  • 8
  • 58
  • 83