使用文件输入创建字典

时间:2018-03-19 15:21:52

标签: python python-3.x dictionary

我有一个格式如下的文件:

Barcelona   2015,2016,2017
Real Madrid   2010
Napoli   2007,2009
Bayern Munich   2008,2009,2010,2011,2012,2013

我想将此保存到包含该团队的字典中,然后将其保存到包含该数字的列表中。我该怎么做?我在分裂方面遇到了一些困难,因为有些球队有更大的名字。

5 个答案:

答案 0 :(得分:4)

这是Pandas解决方案,假设有4个空格分隔符。

import pandas as pd
from io import StringIO

mystr = StringIO("""Barcelona   2015,2016,2017
Real Madrid   2010
Napoli   2007,2009
Bayern Munich   2008,2009,2010,2011,2012,2013""")

df = pd.read_csv(mystr, delimiter='   ', header=None, names=['Club', 'Years'])

df['Years'] = [list(map(int, x)) for x in df['Years'].str.split(',')]
d = df.set_index('Club')['Years'].to_dict()

<强>结果

{'Barcelona': [2015, 2016, 2017],
 'Bayern Munich': [2008, 2009, 2010, 2011, 2012, 2013],
 'Napoli': [2007, 2009],
 'Real Madrid': [2010]}

<强>解释

  • 使用适当的分隔符和名称列读取文件。
  • 用逗号分割,并通过列表推导将每个元素映射到整数类型。
  • 创建由Club编制索引的系列,并使用.to_dict()输出字典。

答案 1 :(得分:1)

您可以使用re分割跨越团队名称和第一位数字的每一行:

import re
final_d = {a:map(int, b.split(',')) for a, b in map(lambda x:re.split('\s+(?=\d)', x.strip('\n')), open('filename.txt').readlines())}

输出:

{'Real Madrid': [2010], 'Bayern Munich': [2008, 2009, 2010, 2011, 2012, 2013], 'Barcelona': [2015, 2016, 2017], 'Napoli': [2007, 2009]}

答案 2 :(得分:1)

试试这个,

            ATOM MyRegisterClass(HINSTANCE hInstance)
            {
                WNDCLASS wc = { 0 };
                wc.style = CS_GLOBALCLASS | CS_HREDRAW | CS_VREDRAW;
                wc.lpfnWndProc = WndProc;
                wc.hCursor = LoadCursor(NULL, IDC_ARROW);
                wc.lpszClassName = _T("CustomControl");
                wc.hbrBackground = (HBRUSH)(COLOR_SCROLLBAR + 1);
                RegisterClass(&wc);

                WNDCLASSEX wcex;
                wcex.cbSize = sizeof(WNDCLASSEX);
                wcex.style = CS_HREDRAW | CS_VREDRAW;
                wcex.lpfnWndProc = WndProc;
                wcex.cbClsExtra = 0;
                wcex.cbWndExtra = 0;
                wcex.hInstance = hInstance;
                wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_SAMPLEAPP2));
                wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
                wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
                wcex.lpszMenuName = NULL;
                wcex.lpszClassName = szWindowClass;
                wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));

                return RegisterClassEx(&wcex);
            }

            LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
            {
                switch (message)
                {
                    case WM_CREATE:
                    {
                        if (NULL == hWndVScrollBar)
                        {
                            int ScrollBarWidth = 50;
                            int ScrollBarHeight = 50;
                            RECT Rect;
                            GetClientRect(hWnd, &Rect);

                            // Create list control
                            hWnBar = CreateWindowEx(0, WC_LISTVIEW, NULL,
                                WS_VISIBLE | WS_CHILD | WS_BORDER | LVS_REPORT,
                                Rect.left + 100, 50,
                                300, 500, hWnd,
                                (HMENU)IDC_EDITBOX,
                                (HINSTANCE)hInst, NULL);

                            LVCOLUMN LVColumn;
                            LVColumn.mask = LVCF_FMT | LVCF_WIDTH | LVCF_TEXT;
                            LVColumn.fmt = LVCFMT_LEFT;
                            LVColumn.cx = 100;
                            LVColumn.pszText = L"Column 1";
                            LVColumn.cchTextMax = lstrlen(L"Column 1");
                            LVColumn.iSubItem = 0;
                            LVColumn.iImage = 0;
                            LVColumn.iOrder = 0;
                            ListView_InsertColumn(hWnBar, 0, &LVColumn);

                            LVColumn.cx = 300;
                            LVColumn.pszText = L"Column 2";
                            LVColumn.cchTextMax = lstrlen(L"Column 2");
                            LVColumn.iSubItem = 0;
                            LVColumn.iImage = 0;
                            LVColumn.iOrder = 0;
                            ListView_InsertColumn(hWnBar, 1, &LVColumn);

                            LVITEM item;
                            item.mask = LVIF_TEXT;
                            item.cchTextMax = 6;
                            TCHAR tzsItem[250] = { 0 };
                            for (int nIndex = 0; nIndex < 200; nIndex++)
                            {
                                item.iSubItem = 0;
                                swprintf_s(tzsItem, TEXT("List Item: %d"), nIndex + 1);
                                item.pszText = tzsItem;
                                item.iItem = 0;
                                ListView_InsertItem(hWnBar, &item);
                            }

                            hWndVScrollBar = CreateWindowEx(0, _T("CustomControl"), NULL,
                                WS_VISIBLE | WS_CHILD,
                                500, 50,
                                50, 500, hWnd,
                                (HMENU)IDC_VSCROLLBAR,
                                (HINSTANCE)hInst, NULL);

                            hWndHScrollBar = CreateWindowEx(0, _T("CustomControl"), NULL,
                                WS_VISIBLE | WS_CHILD,
                                Rect.left + 100, 600,
                                300, 50, hWnd,
                                (HMENU)IDC_HSCROLLBAR,
                                (HINSTANCE)hInst, NULL);
                            if (!hWndVScrollBar)
                                MessageBox(NULL, L"Vertical Scroll Bar Failed.", L"Error", MB_OK | MB_ICONERROR);
                            if (!hWndHScrollBar)
                                MessageBox(NULL, L"Vertical Scroll Bar Failed.", L"Error", MB_OK | MB_ICONERROR);

                            ptrOld = SetWindowLongPtr(hWndVScrollBar, GWLP_WNDPROC, (DWORD_PTR)WndProc);
                        }
                        return 0;
                    }
                    break;
                    case WM_DESTROY:
                        PostQuitMessage(0);
                        break;
                    default:
                        return DefWindowProc(hWnd, message, wParam, lParam);
                }
                return 0;
            }

答案 3 :(得分:1)

根据要求,纯-python解决方案,

  • 非正则表达式
  • 不是一个班轮
  • 非常可读

data = {}
with open('file.txt') as f:
    for line in f:
        city, dates = line.rstrip().rsplit(None, 1)
        data[city] = [int(d) for d in dates.split(',')]

data
{
    "Barcelona": [
        2015,
        2016,
        2017
    ],
    "Real Madrid": [
        2010
    ],
    "Napoli": [
        2007,
        2009
    ],
    "Bayern Munich": [
        2008,
        2009,
        2010,
        2011,
        2012,
        2013
    ]
}

答案 4 :(得分:0)

这是有效的,我不知道它是不是你想要的。

file=open("info.txt", "r")
lines1=file.readlines()
lines=[]
for i in lines1:
    lines.append(i.split("   "))
output={}
for i in lines:
    key=i[0]
    exec("item=("+i[1]+")")
    output[key]=item