将字典保存为CSV文件

时间:2015-04-27 12:42:51

标签: python csv dictionary

我有一本字典,我尝试使用以下代码将数据写入currency.csv文件: 字典的代码是

def _fetch_currencies():
     response =urllib.request.urlopen('http://www.maths.manchester.ac.uk/~vsego/python/currencies.json')
     html = response.read().decode("utf-8")

     currencies = json.loads(html)
     pprint(currencies)

def _save_currencies(currencies):
    with open(('currencies.csv'), 'wt') as my_csv:
        csv_writer = csv.writer(my_csv, delimiter=',')
        csv_writer.writerow(["code","name"])  
        for key,value in currencies.items(): 
            csv_writer.writerow([key,value])

 _save_currencies(_fetch_currencies())

当我返回代码时,我收到错误消息

'AttributeError: 'NoneType' object has no attribute 'items''

如何解决此错误?

2 个答案:

答案 0 :(得分:1)

您需要返回_fetch_currencies()

def _fetch_currencies():
     response =urllib.request.urlopen('http://www.maths.manchester.ac.uk/~vsego/python/currencies.json')
     html = response.read().decode("utf-8")
     return json.loads(html) # <- return 

您不会返回任何值,因此默认情况下,python返回None,因此当您将_fetch_currencies()传递给_save_currencies时,您正在传递None

您也可以传递dict.items并致电csv.writerows

def _save_currencies(currencies):
    with open(('currencies.csv'), 'wt') as my_csv:
        csv_writer = csv.writer(my_csv, delimiter=',')
        csv_writer.writerow(["code","name"])
        csv_writer.writerows(currencies.items())

答案 1 :(得分:0)

错误是因为您从没有任何字典的字典中请求密钥。原因是_fetch_currencies()没有return语句。

def _fetch_currencies():
     response =urllib.request.urlopen('http://www.maths.manchester.ac.uk/~vsego/python/currencies.json')
     html = response.read().decode("utf-8")

     currencies = json.loads(html)
     return currencies

无论如何,这应该有效:

currencies = {}
for key,value in currencies.items(): 
    print key, value

这不起作用:

currencies = None
for key,value in currencies.items(): 
    print key, value