【问题标题】:How can I create a dictionary within a function out of an argument from that function?如何根据该函数的参数在函数内创建字典?
【发布时间】:2017-11-05 05:22:28
【问题描述】:

这是我尝试过的:

def CreateDict(BDF):
    with open('%sdata\\%s.csv' % (mainDir,BDF), mode='r') as infile:
        reader = csv.reader(infile)
        for row in reader:
            key = row[0]
            print("%s%s = %s" % (BDF,[key],row[1:]))

CreateDict(FileName)

Print 给了我正确的答案。但是我想把它放在字典里,而不是把它打印出来。我希望该字典具有 FileName 的名称)。

【问题讨论】:

  • FileName = CreateDict(...)?如果您想将它们放入字典而不是打印,那么这样做。另推荐阅读:nedbatchelder.com/text/names.html
  • 我去看看,谢谢!
  • 我认为使用 return 可能会解决它,再次感谢!
  • 哦,对不起,我没有解释清楚。 Createdict 位于具有多个文件名的 for 循环中。所以我不能只把“FileName”放在那里,因为有 FileName1 和 FileName2 等等。但我确实想要一个名为 FileName1 的字典等等。

标签: python function csv dictionary arguments


【解决方案1】:

创建字典:

def CreateDict(BDF):
    saved={}
    with open('%sdata\\%s.csv' % (mainDir,BDF), mode='r') as infile:
        reader = csv.reader(infile)
        for row in reader:
            key = row[0]
            saved[key]=row[1:]
    return saved

我不知道如何给字典起一个特定的名称,如果您需要保存多个 CSV 文件,您可以使用字典,其中键是文件名:

 fileNames=['test0', 'test1', 'test2']
 all_files={}
 for fileName in fileNames:
     all_files[fileName]=CreateDict(fileName)

【讨论】:

  • 它似乎不起作用。我使用了 print('test0'),它说没有定义 'test0'(我有一个名为 test0 的 csv)。
  • 我已经完成了一半。我试过这样改变最后一行:fileName = CreateDict(fileName)
  • 我不知道如何给变量一个“字符串名称”,所以你不能这样做:print(test0),因为 test0 从未定义,但你可以这样做:print (all_files['test0']),这应该可以工作
  • 我一直在使用它并且它有效。但是有没有一种方法可以自动定义 test0、test1 等,所以我可以使用它来代替 all_files['test0'] ?虽然我认为可以使用它,但我更喜欢能够使用 test0 等。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-27
  • 2015-12-07
  • 1970-01-01
  • 2016-05-03
  • 2020-03-09
相关资源
最近更新 更多