0

I am using the following function to write a given_dict to csv in python and getting following error below. Any idea what I am doing wrong?

 def write_dict_as_csv(given_dict):
    ...     with open('dict.csv', 'wb') as csv_file:
    ...         writer = csv.writer(csv_file)
    ...         writer.writerow(given_dict.keys())
    ...         writer.writerows(zip(*given_dict.values()))

Error:

 >>> write_dict_as_csv(python_csv)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in print_dict_as_csv
TypeError: an integer is required

additional info using a test case:

import csv
#this is a test case which is used to test the functions
def test_normalization_function():
    x1 = {'k1': 'a1', 'k2': 'b1'}
    x2 = {'k2': 'b2', 'k3': 'c2'}
    x3 = {'k1': 'a3'}
    x = [x1,x2,x3]
    y = normalization(x)
   # print('')
    for k in y:
       print('key: {} : {}'.format(k, y[k]))
    with open('mycsvfile.csv', 'wb') as f:  # Just use 'w' mode in 3.x
        w = csv.DictWriter(f, y.keys())
        w.writeheader()
        w.writerow(y)

def normalization(list_of_dict):
    super_dict = {}
    column_counter = 0
    for i_dict in list_of_dict:
        for k, v in i_dict.iteritems():
            if k not in super_dict:
                super_dict[k] = []
                for i in range(column_counter):
                    super_dict[k].append('NONE')
            super_dict[k].append(v)
        column_counter += 1
        for k in super_dict:
            if k not in i_dict:
                super_dict[k].append('NONE')
    return super_dict

output for the code when I run test_normalization_function():

>>> test_normalization_function()
key: k3 : ['NONE', 'c2', 'NONE']
key: k2 : ['b1', 'b2', 'NONE']
key: k1 : ['a1', 'NONE', 'a3']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 11, in test_normalization_function
TypeError: an integer is required

it shows the dictionary can be print. But when I am trying to save it in csv file, it is giving an error.

Dibyendu Dey
  • 349
  • 2
  • 16
  • can you post your entire code? including the call to print – Tyler Cowan Jan 25 '18 at 23:39
  • Have you looked at similar questions, e.g. https://stackoverflow.com/questions/10373247/how-do-i-write-a-python-dictionary-to-a-csv-file – jpp Jan 25 '18 at 23:41
  • @jp_data_analysis that gives an incorrect output, it doesn't throw and exception like this code – roganjosh Jan 25 '18 at 23:42
  • @roganjosh, I think we've identified the problem. What exactly is the input and correct output? Difficult for us to help otherwise. – jpp Jan 25 '18 at 23:43
  • @jp_data_analysis then recommend an [MCVE](https://stackoverflow.com/help/mcve) :) – roganjosh Jan 25 '18 at 23:45
  • this is extremely poor question asking – Tyler Cowan Jan 25 '18 at 23:46
  • 2
    @TylerCowan If I'm not mistaken, you've recently made a similar comment on another post. You have to take the rough (there's plenty of bad questions coming in) with the smooth but you're not doing anything to remedy the issue in your comment, it's just a degrading statement. If you want to help the site, point the OP to resources that might help them improve later questions. – roganjosh Jan 25 '18 at 23:49
  • You should provide a full usage example. Looking at the shared code, doesn't show any method that could/should raise that kind of error, actually tried it with `print_dict_as_csv({"a":[1,2],"b":[3,4]})` and everything works fine. Most likely you are passing some different object as argument. – Lohmar ASHAR Jan 25 '18 at 23:52
  • @roganjosh I asked for entire code including call to print. but as per your recomendation please refer to https://stackoverflow.com/help/how-to-ask for help in asking better questions – Tyler Cowan Jan 25 '18 at 23:52
  • thank you all for prompt response. I can't share the "given_dict" code which has some confidentiality info. Here purpose is to save a dictionary into csv. I will look into the suggested link. Sorry I can't provide more info. – Dibyendu Dey Jan 25 '18 at 23:53
  • @DibyenduDey You can _always_ provide more info because you should reduce your problem down to a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) which will abstract away all confidential info. – roganjosh Jan 25 '18 at 23:54
  • In line 2, there is `with open('dict.csv', 'wb') as csv_file:` which does not throw `TypeError: an integer is required` unless you've erroneously clobbered the builtin `open()` with `os.open()`. See the dupe target. – TemporalWolf Jan 26 '18 at 00:02
  • ok. I have added a test case dictionary. It can be printed but giving an error when trying to put it in .csv. – Dibyendu Dey Jan 26 '18 at 00:24
  • Finally the issue is resolved. Thanks @TemporalWolf I am using a client where open is interpreted as os.open() it might be because of from os import * issue. I imported io. used io.open() instead and it worked. Thanks all! – Dibyendu Dey Jan 26 '18 at 01:31

0 Answers0