附加多个字典元素以列出

时间:2017-11-11 18:53:19

标签: python list dictionary

我有一个包含多个词典的大列表,例如我可以访问:

papers = []   # the list of dictionaries

for each in range(0, len(papers)):
    out = []
    try:
        out.append(str(papers[each]['TI']) + "\n" + str(papers[each]['AB']) + "\n" + str(papers[each]['MH']) + "\n")
    except KeyError:
        out.append("MISSING INFORMATION \n")

for index, line in enumerate(out):
    with open(filename+'_{}.txt'.format(index), 'w') as output:
        output.write(line)

我需要访问列表中所有词典的3个不同键(['TI'],['AB']和['MH']),然后将它们打印到.txt文件中,但目前我的代码只打印出所有词典中的一个键(['TI'])。这就是我所拥有的:

TypeError: cannot concatenate 'str' and 'list' objects

注意:我在每个论文密钥中添加了str(),因为我一直收到这个错误:

Public Function MostRecentFile(ByVal searchDirectory As String, ByVal wildCard As String) As String
    '''Returns the most recent file in searchDirectory, which matches wildCard criteria
    Dim strFile As String                        'holds the name of the file we're currently looking at
    Dim mostRecent As Date                       'holds the date of creation for the most recent file
    Dim currDate As Date                         'date of creation for the current file
    Dim mostRecentPath As String                 'path of file with most recent date

    strFile = Dir(searchDirectory & wildCard)    'look for file in directory which matches wildcard
    Do While Len(strFile) > 0                    'loop until Dir returns empty quotes (no files)
        currDate = FileDateTime(searchDirectory & strFile)
        If currDate > mostRecent Then            'check whether current file is more recent than previous files
            mostRecent = currDate                'if so, update most recent date and file
            mostRecentPath = searchDirectory & strFile
        End If
        strFile = Dir                            'move to next file in directory
    Loop

    If mostRecent = 0 Then                       'check whether any files were returned
        MostRecentFile = "No files match '" & searchDirectory & wildCard & "'"
    Else
        MostRecentFile = mostRecentPath
    End If
End Function

可能有什么问题,因为我无法打印3个不同的键而只能打印一个?任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:1)

我可能会这样做:

papers = []   # the list of dictionaries
out = []
# ...
# populate your papers list
# ...
for paper in papers:
    try:
        paper_string = "{TH}\n{AB}\n{MH}\n".format(
            TH=paper['TH'],
            AB=paper['AB'],
            MH=paper['MH'])
     except KeyError:
         paper_string = "MISSING INFORMATION\n"
     finally:
         out.append(paper_string)

答案 1 :(得分:1)

问题是你的out = []在for循环中。每次迭代,它都会重新初始化为空白列表。

一些小建议:

  1. 只需在论文中使用(不需要范围)

  2. 获取字符串的键,您可以使用每个[键],因为每个 表示循环正在查看的论文中的当前条目。

  3. 如果您只想安静地查看您的论文列表,您可以在不使用try / except的情况下执行此操作,使用ifs确保您不会创建缺少键的异常。这是我的测试代码:

    dict1 = {'TI':'baa', 'AB':'baar', 'MH':'maa', 'DK':'maar'} # all keys and more
    dict2 = {'TI':'baa', 'AB':'baar', 'MH':'maa', 'DK':'maar'} 
    dict3 = {'OG':'moo', 'AG':'moor', 'ND':'raa', 'DG':'raar'} # none of the keys
    dict4 = {'TI':'baa', 'AG':'moor', 'MH':'maa', 'DG':'raar'} # Two of the keys 
    
    
    papers = [dict1, dict2, dict3, dict4]
    
    out = []
    
    for paper in papers: # Automatically iterates over all list entries in papers.
    
    
        # if all papers always have all three keys:
        ##results = ''.join((paper['TI'], '\n', paper['AB'], '\n', paper['MH']))
    
        ##out.append(results)
    
        # OR: If they may have only (any) one of the keys:
    
        results = ''
    
        if 'TI' in paper: results+=paper['TI']
        if 'AB' in paper: results+='\n'+paper['AB']
        if 'MH' in paper: results+='\n'+paper['MH']
    
        out.append(results)
    

    这是第二个版本:

      

    ['baa \ nbaar \ nmaa','baa \ nbaar \ nmaa','','baa \ nmaa']

答案 2 :(得分:0)

试试这段代码:

papers=[]
out = []

for index,value in enumerate(papers):
    try:
        out.append(str(papers[index]['TH']) + "\n" + str(papers[index]['AB']) + "\n" + str(papers[index]['MH']) + "\n")
    except KeyError:
        out.append("MISSING INFORMATION \n")

    print(out)