code:
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 20 14:30:55 2023
@author: SavingKing
"""
sample_dict = {
"name": "Alice",
"age": 30,
"city": "Wonderland"
}
import json
# 直接将字典序列化到文件
with open("output_with_dump.json", "w") as file:
json.dump(sample_dict, file, indent=4)
# 先将字典序列化为字符串,然后写入文件
json_str = json.dumps(sample_dict, indent=4)
with open("output_with_dumps.json", "w") as file:
file.write(json_str)code & 輸出結果:

两个文件 output_with_dump.json 和 output_with_dumps.json 将包含相同的JSON内容,但是生成这些文件的过程不同。json.dump() 是一步到位的方法,直接将对象写入文件;而json.dumps() 则是一个两步的过程,先创建字符串,然后将其写入文件。在结果上,两者是等效的:

推薦hahow線上學習python: https://igrape.net/30afN
![Python:如何用pandas.concat() 合併兩個DataFrame並重置index? pd.concat([df1, df2]) .reset_index(drop=True) ; pd.concat([df1, df2], ignore_index=True) Python:如何用pandas.concat() 合併兩個DataFrame並重置index? pd.concat([df1, df2]) .reset_index(drop=True) ; pd.concat([df1, df2], ignore_index=True)](https://i2.wp.com/savingking.com.tw/wp-content/uploads/2023/03/20230311123232_5.png?quality=90&zoom=2&ssl=1&resize=350%2C233)


![Python: 如何將pandas.DataFrame從寬資料轉為長資料? df_melt = pd.melt(df, id_vars=[‘name’, ‘gender’], var_name=’time’, value_name=’score’) ; seaborn繪圖 Python: 如何將pandas.DataFrame從寬資料轉為長資料? df_melt = pd.melt(df, id_vars=[‘name’, ‘gender’], var_name=’time’, value_name=’score’) ; seaborn繪圖](https://i2.wp.com/savingking.com.tw/wp-content/uploads/2023/03/20230302152215_95.png?quality=90&zoom=2&ssl=1&resize=350%2C233)






近期留言