开发者

Learning Python: Store values in dict from stdout

开发者 https://www.devze.com 2023-02-21 17:07 出处:网络
How can I do the following in Python: I have a command output that outputs this: Datexxxx Clientxxx Timexxx

How can I do the following in Python: I have a command output that outputs this:

Datexxxx
Clientxxx
Timexxx

Datexxxx
Client2xxx
Timexxx

Datexxxx
Client3xxx
Timexxx

And I want to work this in a dict like:

Client:(date,time), Client2:(da开发者_如何学Gote,time) ...


After reading the data into a string subject, you could do this:

import re
d = {}
for match in re.finditer(
    """(?mx)
       ^Date(.*)\r?\n
       Client\d*(.*)\r?\n
       Time(.*)""", 
    subject):
        d[match.group(2)] = (match.group(1), match.group(2))


How about something like:

rows = {}
thisrow = []

for line in output.split('\n'):
        if line[:4].lower() == 'date':
                thisrow.append(line)
        elif line[:6].lower() == 'client':
                thisrow.append(line)
        elif line[:4].lower() == 'time':
                thisrow.append(line)
        elif line.strip() == '':
                rows[thisrow[1]] = (thisrow[0], thisrow[2])
                thisrow = []

print rows

Assumes a trailing newline, no spaces before lines, etc.


What about using a dict with tuples? Create a dictionary and add the entries:

dict = {}
dict['Client'] = ('date1','time1')
dict['Client2'] = ('date2','time2')

Accessing the entires:

dict['Client']
>>> ('date1','time1')
0

精彩评论

暂无评论...
验证码 换一张
取 消