簡體   English   中英

如何將列表轉換為字典?

[英]How to convert a list to a dict?

我正在使用subprocess進程打印ls的 output 。

output = subprocess.getoutput("ssh -i key.pem ubuntu@10.127.6.83 ls -l --time-style=long-iso /opt/databases | awk -F' ' '{print $6 $8}'")
lines = output.splitlines()
print(lines)
format = '%Y-%m-%d'
for line in lines:
   if line != '':
      date = datetime.strptime(line, format)

當我打印行時,我會得到以下格式的大列表:

['', '2019-04-25friendship_graph_43458', '2019-07-18friendship_graph_45359', '2019-09-03friendship_graph_46553', '2019-10-02friendship_graph_46878']

我正在嘗試將上述 output 轉換為日期為'%Y-%m-%d'格式的字典。 所以 output 會是這樣的:

{ '2019-04-25' : 'friendship_graph_43458',
  '2019-07-18': 'friendship_graph_45359',
  '2019-09-03': 'friendship_graph_46553' }

等等,但不太確定該怎么做。

從技術上講,如果您不想使用re如果所有日期的格式都相同,那么它們都將是 10 個字符長,因此只需對字符串進行切片以使 dict 理解:

data = ['', '2019-04-25friendship_graph_43458', '2019-07-18friendship_graph_45359', '2019-09-03friendship_graph_46553', '2019-10-02friendship_graph_46878']

output = {s[:10]: s[10:] for s in data if len(s) > 10}

{'2019-04-25': 'friendship_graph_43458', '2019-07-18': 'friendship_graph_45359', '2019-09-03': 'friendship_graph_46553', '2019-10-02': 'friendship_graph_46878'}

您可以對列表中的每個項目使用正則表達式。 例如:

(\d{4}-\d{2}-\d{2})(.*)

然后,您可以遍歷列表中的每個項目並使用正則表達式來獲取其兩部分中的字符串。

>>> import re
>>> regex = re.compile(r"(\d{4}-\d{2}-\d{2})(.*)")
>>> items = ['', '2019-04-25friendship_graph_43458', '2019-07-18friendship_graph_45359', '2019-09-03friendship_graph_46553', '2019-10-02friendship_graph_46878']
>>> items_dict = {}
>>> for i in items:
        match = regex.search(i)
        if match is None:
            continue
        items_dict[match.group(1)] = match.group(2)

    
>>> items_dict
{'2019-04-25': 'friendship_graph_43458', '2019-07-18': 'friendship_graph_45359', '2019-09-03': 'friendship_graph_46553', '2019-10-02': 'friendship_graph_46878'}

對於以日期開頭的行; 使用切片將鍵與值分開。

>>> s = '2019-04-25friendship_graph_43458'
>>> d = {}
>>> d[s[:10]] = s[10:]
>>> d
{'2019-04-25': 'friendship_graph_43458'}
>>>

使用re.findall字典理解

import re
lst = ['', '2019-04-25friendship_graph_43458', '2019-07-18friendship_graph_45359', '2019-09-03friendship_graph_46553', '2019-10-02friendship_graph_46878']
dct = {k: v for s in lst for k, v in re.findall(r'(\d\d\d\d-\d\d-\d\d)(.*)', s) }
print(dct)
# {'2019-04-25': 'friendship_graph_43458', '2019-07-18': 'friendship_graph_45359', '2019-09-03': 'friendship_graph_46553', '2019-10-02': 'friendship_graph_46878'}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM