如何将一个词典列表添加到另一个词典列表?
我正在使用 for 循环将字典添加到字典列表(我称之为 data_file),使用 data_file.append()
它工作正常:)但后来我尝试在另一个中向 data_file 添加更多字典for 循环,我再次使用 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"
I'm using a for loop to add a dictionary to a list of dictionaries (which I'm calling data_file), using data_file.append()
It works fine :) But then later I try to add some more dictionaries to data_file in another for loop and I use data_file.append() again and it doesn't work. It doesn't add those dictionaries to data_file
Does anyone know what I'm doing wrong?
I don't get an error. It just produces a file that only has the dictionaries from massage_generators. It doesn't take on anything from travel_generators.
I've even tried commenting out the first for loop, the one for massage_generators, and in that case it does add in the travel_generators dictionaries. It's like I can't use .append() twice?
Any help would be much appreciated please!
I'm sorry it's not very elegant, I'm only just learning this coding stuff! :)
Thanks
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"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在您提供的示例中,
generators
、travel_generators
和massage_generators
都是相同的,并且每个都包含相同的open_file
实例代码>.当您迭代massage_generators
时,您将到达文件末尾。然后,当您迭代travel_generators
时,open_file
中没有任何内容可供迭代。至少,您可以更改以下行:
To:
open_file
现在是一个列表而不是生成器,并且可以迭代和重新迭代。但是,我建议您迭代该文件一次,并构建两个字典,并在每次迭代中写入
DictWriter
实例。In the example you provided,
generators
,travel_generators
, andmassage_generators
are all identical, and each contain the same instance ofopen_file
. When you iteratemassage_generators
, you reach the end of the file. Then when you iteratetravel_generators
, there's nothing left to iterate inopen_file
.At the very least, you could change the following line:
To:
open_file
is now a list and not a generator and can be iterated and re-iterated.However, I would recommend you iterate through the file once, and build your two dictionaries, and write to a
DictWriter
instance in each iteration.这是您的问题:
您的
travel_generators
和massage_generators
列表使用相同的打开文件来迭代并获取数据;问题是,一旦文件被massage_generators
中的csv.DictReader
迭代一次,它就已经耗尽,当您尝试读取它时,您将无法获得更多数据再次在travel_generators
中。请尝试以下操作:
然后在循环中:
另外,在收集文件名的第一个循环中:请注意,循环仅保存匹配的最后文件名。如果这是您的意图,您可以通过在
travel = filename
后面的行中添加break
来明确表示。Here's your problem:
Your
travel_generators
andmassage_generators
lists are using the same open file to iterate over and get data; the problem with that is once the file has been iterated over once by thecsv.DictReader
inmassage_generators
it has been exhausted and you get no more data when you try to read it again intravel_generators
.Try this instead:
and then in your loops:
Also, in your first loop where you are gathering filenames: be aware that the loop is only saving the last filename that matches. If that is your intention you can make it clear by adding
break
on the line aftertravel = filename
.