简体   繁体   中英

How to covert python dict to csv file, where keys will be column?

I;m trying to convert a python dictionary to contents of csv file where all keys will be column names and values of dict will be rows, using from_dict() throws a value error.

dict = { 'Name' : 'ABC', 'Number': 123}

df = pd.DataFrame.from_dict(dict)
print(df)
df.to_csv(r'C:\Users\Desktop\data.csv')

Error:
Traceback (most recent call last):
  File "C:/Users/PycharmProjects/PythonTest/Test3.py", line 73, in <module>
    df = pd.DataFrame.from_dict(epprom_data)
  File "C:\Users\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\frame.py", line 1373, in from_dict
    return cls(data, index=index, columns=columns, dtype=dtype)
  File "C:\Users\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\frame.py", line 529, in __init__
    mgr = init_dict(data, index, columns, dtype=dtype)
  File "C:\Users\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\internals\construction.py", line 287, in init_dict
    return arrays_to_mgr(arrays, data_names, index, columns, dtype=dtype)
  File "C:\Users\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\internals\construction.py", line 80, in arrays_to_mgr
    index = extract_index(arrays)
  File "C:\Users\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\internals\construction.py", line 391, in extract_index
    raise ValueError("If using all scalar values, you must pass an index")
ValueError: If using all scalar values, you must pass an index

Desired output: Excel file with below contents:

               Name    Number
1              ABC      123

To elaborate on what @Corralien said above, pandas expects a non-string sequence of values when trying to convert a dictionary to a DataFrame So:

data_dict = { 'Name' : 'ABC', 'Number': 123}

df = pd.DataFrame.from_dict(data_dict)
print(df)
df.to_csv(r'C:\Users\Desktop\data.csv')

Fails because 'ABC' and 123 aren't lists or arrays of values.

and simply converting to

data_dict = { 'Name' : ['ABC'], 'Number': [123]}

df = pd.DataFrame.from_dict(data_dict)
print(df)
df.to_csv(r'C:\Users\Desktop\data.csv')

Resolves the issue

Try as suggested by @ifly6:

# PLEASE DON'T USE BUILTIN AS VARIABLE NAME (dict, list, set, sum, ...)
d = { 'Name' : ['ABC'], 'Number': [123]}
# Use list     ^     ^            ^   ^

pd.DataFrame(d)
print(df)
  Name  Number
0  ABC     123

Another solution is to use the orient='index' parameter and transpose .T your series to a dataframe.

Demo:

d = { 'Name' : ['ABC'], 'Number': [123]}

df = pd.DataFrame.from_dict(d, orient='index').T
print(df)
  Name Number
0  ABC    123

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