如何将一个词典列表添加到另一个词典列表?

发布于 2024-12-12 03:51:23 字数 2837 浏览 0 评论 0原文

我正在使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

幼儿园老大 2024-12-19 03:51:24

在您提供的示例中,generatorstravel_generatorsmassage_generators 都是相同的,并且每个都包含相同的 open_file 实例代码>.当您迭代massage_generators时,您将到达文件末尾。然后,当您迭代 travel_generators 时,open_file 中没有任何内容可供迭代。

至少,您可以更改以下行:

open_file = csv.DictReader(open(travel))

To:

open_file = map(None, csv.DictReader(open(travel)))

open_file 现在是一个列表而不是生成器,并且可以迭代和重新迭代。

但是,我建议您迭代该文件一次,并构建两个字典,并在每次迭代中写入 DictWriter 实例。

open_file = csv.DictReader(open(travel))
...
dict_writer = csv.DictWriter(bulk_upload, keys, restval='', extrasaction='ignore')
dict_writer.writer.writerow(keys)

for line in open_file:
    massage_dictionary={}
    massage_dictionary.update(line)
    ... # manipulate massage_dictionary
    dict_writer.writerow(massage_dictionary)

    travel_dictionary={}
    travel_dictionary.update(line)
    ... # manipulate travel_dictionary
    dict_writer.writerow(travel_dictionary)

In the example you provided, generators, travel_generators, and massage_generators are all identical, and each contain the same instance of open_file. When you iterate massage_generators, you reach the end of the file. Then when you iterate travel_generators, there's nothing left to iterate in open_file.

At the very least, you could change the following line:

open_file = csv.DictReader(open(travel))

To:

open_file = map(None, csv.DictReader(open(travel)))

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.

open_file = csv.DictReader(open(travel))
...
dict_writer = csv.DictWriter(bulk_upload, keys, restval='', extrasaction='ignore')
dict_writer.writer.writerow(keys)

for line in open_file:
    massage_dictionary={}
    massage_dictionary.update(line)
    ... # manipulate massage_dictionary
    dict_writer.writerow(massage_dictionary)

    travel_dictionary={}
    travel_dictionary.update(line)
    ... # manipulate travel_dictionary
    dict_writer.writerow(travel_dictionary)
流殇 2024-12-19 03:51:23

这是您的问题:

open_file = csv.DictReader(open(travel))
generators.append(open_file)    

travel_generators = generators[:]
massage_generators = generators[:]

您的 travel_generatorsmassage_generators 列表使用相同的打开文件来迭代并获取数据;问题是,一旦文件被 massage_generators 中的 csv.DictReader 迭代一次,它就已经耗尽,当您尝试读取它时,您将无法获得更多数据再次在 travel_generators 中。

请尝试以下操作:

generators.append(travel)     # just the filename    

travel_generators = generators[:]
massage_generators = generators[:]

然后在循环中:

for filename in massage_generators:
    for dictionary in csv.DictReader(open(filename)):

另外,在收集文件名的第一个循环中:请注意,循环仅保存匹配的最后文件名。如果这是您的意图,您可以通过在 travel = filename 后面的行中添加 break 来明确表示。

Here's your problem:

open_file = csv.DictReader(open(travel))
generators.append(open_file)    

travel_generators = generators[:]
massage_generators = generators[:]

Your travel_generators and massage_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 the csv.DictReader in massage_generators it has been exhausted and you get no more data when you try to read it again in travel_generators.

Try this instead:

generators.append(travel)     # just the filename    

travel_generators = generators[:]
massage_generators = generators[:]

and then in your loops:

for filename in massage_generators:
    for dictionary in csv.DictReader(open(filename)):

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 after travel = filename.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文