我正在使用for循環來添加字典到字典列表(我打電話data_file),使用data_file.append()如何將詞典列表添加到另一個詞典列表?
它工作正常:)但後來我嘗試添加一些更多的字典data_file在另一個循環,我再次使用data_file.append(),它不起作用。它不會將這些字典添加到data_file
有誰知道我在做什麼錯?
我沒有收到錯誤。它只產生一個只有來自massage_generators的字典的文件。它不包含travel_generators中的任何內容。
我甚至試過註釋掉第一個for循環,第一個用於massage_generators,在那種情況下,它添加在travel_generators字典中。這就像我不能使用.append()兩次?
任何幫助將不勝感激請!
對不起,它不是很優雅,我只是在學習這個編碼的東西! :)
感謝
import csv
import copy
import os
import sys
generators = list()
for filename in os.listdir(os.getcwd()):
root, ext = os.path.splitext(filename)
if root.startswith('Travel Allowance Auto Look up') and ext == '.csv':
travel = filename
open_file = csv.DictReader(open(travel))
generators.append(open_file)
travel_generators = generators[:]
massage_generators = generators[:]
data_file = [] # result will be stored here (List of dicts)
travel_remap = {'FINAL_TRAVEL_ALL':'AMOUNT'}
massage_remap = {'MASSAGE_BIK':'AMOUNT'}
for generator in massage_generators:
for dictionary in generator:
dictionary['PAYMENT_TYPE_CODE'] = 'MASSAGE_BIK'
dictionary['COMMENT'] = 'Massage BIK'
dictionary['IS_GROSS'] = 'FALSE'
dictionary['PAYMENT_TO_DATE'] = '01/01/2099'
dictionary['PAID MANUALLY'] = 'FALSE'
for old_key, new_key in massage_remap.iteritems():
if old_key not in dictionary:
continue
dictionary['AMOUNT'] = dictionary['MASSAGE_BIK']
del dictionary['MASSAGE_BIK']
if (dictionary['AMOUNT'] != '0' and dictionary['AMOUNT'] != ''):
data_file.append(dictionary)
for generator in travel_generators:
for dictionary in generator:
dictionary['PAYMENT_TYPE_CODE'] = 'TRANSPORTATION_ALLOWANCE'
dictionary['COMMENT'] = 'Annual travel allowance paid in monthly installments'
dictionary['IS_GROSS'] = 'TRUE'
dictionary['PAYMENT_TO_DATE'] = '01/01/2099'
dictionary['PAID MANUALLY'] = 'FALSE'
for old_key, new_key in travel_remap.iteritems():
if old_key not in dictionary:
continue
dictionary['AMOUNT'] = dictionary['FINAL_TRAVEL_ALL']
del dictionary['FINAL_TRAVEL_ALL']
if (dictionary['AMOUNT'] != 'Not Applicable' and dictionary['AMOUNT'] != '0' and dictionary['AMOUNT'] != '' and dictionary['AMOUNT'] != '#N/A'):
data_file.append(dictionary)
keys = ['EMPID', 'Common Name', 'PAYMENT_TYPE_CODE', 'CURRENCY', 'AMOUNT', 'EFFECTIVE_DATE',
'COMMENT', 'PAYMENT_FROM_DATE', 'PAYMENT_TO_DATE', 'IS_GROSS', 'HIDDEN_UNTIL', 'PAID MANUALLY', 'PAYMENT_DATE']
bulk_upload = open('EMEA Bulk Upload.csv', 'wb')
dict_writer = csv.DictWriter(bulk_upload, keys, restval='', extrasaction='ignore')
dict_writer.writer.writerow(keys)
dict_writer.writerows(data_file)
print "Everything saved! Look up EMEA Bulk Upload.csv"
您是否收到錯誤消息?你能發佈你的代碼嗎? – thegrinner
嗨!我沒有收到任何錯誤,只是第二次添加任何內容而沒有添加任何內容。我已經添加了我的代碼,對不起,這不是很好看! –
在每個'data_file.append(dictionary)'之前用'print len(data_file),dictionary'添加一行並檢查它是否正在打印您正在等待的數據。 – eumiro