简体   繁体   English

Python将字典转换为CSV

[英]Python convert dictionary to CSV

I am trying to convert dictionary to CSV so that it is readable (in their respective key). 我正在尝试将字典转换为CSV,以便可读(在它们各自的键中)。

import csv
import json
from urllib.request import urlopen
x =0
id_num = [848649491, 883560475, 431495539, 883481767, 851341658, 42842466, 173114302, 900616370, 1042383097, 859872672]
for bilangan in id_num:

with urlopen("https://shopee.com.my/api/v2/item/get?itemid="+str(bilangan)+"&shopid=1883827")as response:
    source = response.read()

data = json.loads(source)
#print(json.dumps(data, indent=2))


data_list ={ x:{'title':productName(),'price':price(),'description':description(),'preorder':checkPreorder(),
             'estimate delivery':estimateDelivery(),'variation': variation(), 'category':categories(),
             'brand':brand(),'image':image_link()}}

#print(data_list[x])
x =+ 1

i store the data in x , so it will be looping from 0 to 1, 2 and etc. i have tried many things but still cannot find a way to make it look like this or close to this: 我将数据存储在x ,因此它将从0循环到1、2等。我尝试了很多事情,但仍然找不到找到使其看起来像或接近这样的方法:

https://i.stack.imgur.com/WoOpe.jpg https://i.stack.imgur.com/WoOpe.jpg

Using DictWriter from the csv module csv模块使用DictWriter

Demo: 演示:

import csv

data_list ={'x':{'title':'productName()','price':'price()','description':'description()','preorder':'checkPreorder()',
             'estimate delivery':'estimateDelivery()','variation': 'variation()', 'category':'categories()',
             'brand':'brand()','image':'image_link()'}}

with open(filename, "w") as infile:
    writer = csv.DictWriter(infile, fieldnames=data_list["x"].keys())
    writer.writeheader()
    writer.writerow(data_list["x"])

I think, maybe you just want to merge some cells like excel do? 我认为,也许您只是想像excel一样合并一些单元格? If yes, I think this is not possible in csv, because csv format does not contain cell style information like excel. 如果是,我认为这在csv中是不可能的,因为csv格式不包含像excel这样的单元格样式信息。 Some possible solutions: 一些可能的解决方案:

  1. use openpyxl to generate a excel file instead of csv, then you can merge cells with "worksheet.merge_cells()" function. 使用openpyxl而不是csv来生成excel文件,然后可以使用“ worksheet.merge_cells()”功能合并单元格。
  2. do not try to merge cells, just keep title, price and other fields for each line, the data format should be like: 不要尝试合并单元格,只需保留每行的标题,价格和其他字段,数据格式应类似于:

    first line: {'title':'test_title', 'price': 22, 'image': 'image_link_1'} 第一行:{'title':'test_title','price':22,'image':'image_link_1'}

    second line: {'title':'test_title', 'price': 22, 'image': 'image_link_2'} 第二行:{'title':'test_title','price':22,'image':'image_link_2'}

  3. do not try to merge cells, but set the title, price and other fields to a blank string, so it will not show in your csv file. 不要尝试合并单元格,而是将标题,价格和其他字段设置为空字符串,这样它就不会显示在csv文件中。

  4. use line break to control the format, that will merge multi lines with same title into single line. 使用换行符来控制格式,它将具有相同标题的多行合并为单行。

hope that helps. 希望能有所帮助。

If I were you, I would have done this a bit differently. 如果我是你,我会做得有些不同。 I do not like that you are calling so many functions while this website offers a beautiful JSON response back :) More over, I will use pandas library so that I have total control over my data. 我不喜欢您在该网站提供漂亮的JSON响应的同时调用了这么多函数:)而且,我将使用pandas库,以便完全控制我的数据。 I am not a CSV lover. 我不是CSV爱好者。 This is a silly prototype: 这是一个愚蠢的原型:

import requests
import pandas as pd

# Create our dictionary with our items lists

data_list = {'title':[],'price':[],'description':[],'preorder':[],
             'estimate delivery':[],'variation': [], 'categories':[],
             'brand':[],'image':[]}

# API url
url ='https://shopee.com.my/api/v2/item/get' 

id_nums = [848649491, 883560475, 431495539, 883481767, 851341658,
          42842466, 173114302, 900616370, 1042383097, 859872672]
shop_id = 1883827

# Loop throw id_nums and return the goodies
for id_num in id_nums:
    params = {
         'itemid': id_num, # take values from id_nums 
        'shopid':shop_id}
    r = requests.get(url, params=params)

    # Check if we got something :)
    if r.ok:
        data_json = r.json()

        # This web site returns a beautiful JSON we can slice :)

        product = data_json['item']

        # Lets populate our data_list with the items we got. We could simply
        # creating one function to do this, but for now this will do
        data_list['title'].append(product['name'])
        data_list['price'].append(product['price'])
        data_list['description'].append(product['description'])
        data_list['preorder'].append(product['is_pre_order'])
        data_list['estimate delivery'].append(product['estimated_days'])
        data_list['variation'].append(product['tier_variations'])
        data_list['categories'].append([product['categories'][i]['display_name'] for i, _ in enumerate(product['categories'])])
        data_list['brand'].append(product['brand'])
        data_list['image'].append(product['image'])

    else:
            # Do something if we hit connection error or something.
            # may be retry or ignore
            pass



# Putting dictionary to a list and ordering :)
df = pd.DataFrame(data_list)
df = df[['title','price','description','preorder','estimate delivery',
         'variation', 'categories','brand','image']]

# df.to ...? There are dozen of different ways to store your data 
# that are far better than CSV, e.g. MongoDB, HD5 or compressed pickle

df.to_csv('my_data.csv', sep = ';', encoding='utf-8', index=False)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM