从文本文件创建字典

时间:2016-10-28 21:30:44

标签: python file dictionary

如何从文本文件创建字典?我不想在文本文件本身中有任何特殊之处,因为我想直接从Python写入文件。

文字档案:

Soda $2 Burger $5 Shake $4 Fries $3

代码:

file = 'file.dat'
filer = open(file, "r")
food = {}
for i in filer:
    x = i.split(" ")
    for i in range(len(x)):
        if i %2 == 0:
            a = x[i]
        else:
            b = x[i]
        food[a] = b

2 个答案:

答案 0 :(得分:1)

  

哦拍它有效!

不,它不应该。它应该给你一个" NameError:name' b'没有定义"信息。如果' a'已设置,然后' b'当food[a] = [b]发生时,要么未设置,要么从之前的交互中遗留下来。更方便的方法可能是:

file_name = 'file.dat'

food = {}

with open(file_name) as file:
    for line in file:
        pairs = line.split()
        food.update(zip(pairs[0::2], pairs[1::2]))

<强>产生

{'Shake': '$4', 'Fries': '$3', 'Soda': '$2', 'Burger': '$5'}

答案 1 :(得分:0)

如果你控制格式,你应该只使用json

    Private Type BROWSEINFO ' used by the function GetFolderName
    hOwner As Long
    pidlRoot As Long
    pszDisplayName As String
    lpszTitle As String
    ulFlags As Long
    lpfn As Long
    lParam As Long
    iImage As Long
    End Type
    Private Declare Function SHGetPathFromIDList Lib "shell32.dll" _
    Alias "SHGetPathFromIDListA" (ByVal pidl As Long, ByVal pszPath As String) As Long
Private Declare Function SHBrowseForFolder Lib "shell32.dll" _
    Alias "SHBrowseForFolderA" (lpBrowseInfo As BROWSEINFO) As Long

Function GetFolderName(Msg As String) As String
' returns the name of the folder selected by the user
Dim bInfo As BROWSEINFO, path As String, r As Long
Dim X As Long, pos As Integer
    bInfo.pidlRoot = 0& ' Root folder = Desktop
    If IsMissing(Msg) Then
        bInfo.lpszTitle = "Select a folder."
        ' the dialog title
    Else
        bInfo.lpszTitle = Msg ' the dialog title
    End If
    bInfo.ulFlags = &H1 ' Type of directory to return
    X = SHBrowseForFolder(bInfo) ' display the dialog
    ' Parse the result
    path = Space$(512)
    r = SHGetPathFromIDList(ByVal X, ByVal path)
    If r Then
        pos = InStr(path, Chr$(0))
        GetFolderName = Left(path, pos - 1)
    Else
        GetFolderName = ""
    End If
End Function

Public Function FileFolderExists(strFullPath As String) As Boolean

'Macro Purpose: Check if a file or folder exists

    On Error GoTo EarlyExit
    If Not (Dir(strFullPath, vbDirectory) = vbNullString) Then FileFolderExists = True

EarlyExit:
    On Error GoTo 0

End Function