JavaScript
x
23
23
1
Sample data:-
2
3
Group Information:
4
Name Target Status Role Mode Options
5
SG_hpux_vgcgloack.r518634 s2976 Started Primary Sync auto_recover,auto_failover,path_management,auto_synchronize,active_active
6
LocalVV ID RemoteVV ID SyncStatus LastSyncTime
7
vgcglock_SG_cluster 13496 vgcglock_SG_cluster 28505 Synced NA
8
9
Name Target Status Role Mode Options
10
aix_rcg1_AA.r518634 s2976 Started Primary Sync auto_recover,auto_failover,path_management,auto_synchronize,active_active
11
LocalVV ID RemoteVV ID SyncStatus LastSyncTime
12
tpvvA_aix_r.2 20149 tpvvA_aix.2 41097 Synced NA
13
tpvvA_aix_r.3 20150 tpvvA_aix.3 41098 Synced NA
14
tpvvA_aix_r.4 20151 tpvvA_aix.4 41099 Synced NA
15
16
17
Name Target Status Role Mode Options
18
aix_rcg2_AA.r518634 s2976 Started Primary Sync auto_recover,auto_failover,path_management,auto_synchronize,active_active
19
LocalVV ID RemoteVV ID SyncStatus LastSyncTime
20
decoA_aix_r.11 20158 decoA_aix.11 41106 Synced NA
21
decoA_aix_r.12 20159 decoA_aix.12 41107 Synced NA
22
decoA_aix_r.13 20160 decoA_aix.13 41108 Synced NA
23
I want to search for line “Name” and the immediate next line and use it as Key: Value.
Code:-
JavaScript
1
17
17
1
##The file is large and the code not shown here extract the data from Group Information line
2
##and saves to "no_extra_lines.
3
4
# here i am removing the empty lines or empty strings
5
no_extra_lines = [line for line in required_lines if line.strip() != ""]
6
print(no_extra_lines)
7
print(len(no_extra_lines))
8
9
10
#here i want to iterrate over the string and want to extract the line "Name" and the immedite next line.
11
for num, line in enumerate(no_extra_lines):
12
print(num, line)
13
if "Name" in line:
14
print(line)
15
print(line +1)
16
17
How to print the line and the next line? OR to put it in another way, how can I extract the next set of lines after every occurrence of “Name”. The list is huge with the same pattern. I want to extract these 2 lines for every occurance and save as a key-value.
Advertisement
Answer
Since you have said that ‘The list is huge’, I would suggest to use an approach that uses iteration only and avoids indexing:
JavaScript
1
11
11
1
def extract_name_next(lines):
2
it = (line for line in lines if line.strip() != '')
3
for line in it:
4
if line.startswith('Name'):
5
key = line
6
try:
7
value = next(it)
8
yield key, value
9
except StopIteration:
10
raise ValueError('Name must be followd by additional line')
11
This is a generator function that yields (key, value) pair. To print you can use it like
JavaScript
1
4
1
for key, value in extract_name_next(required_lines):
2
print(key)
3
print(value)
4
You could also construct a dict from these pairs:
JavaScript
1
2
1
mydict = dict(extract_name_next(required_lines))
2
Note that you could aswell use this generator to extract key,value pairs from e.g. a file, even if the file does not fit into RAM:
JavaScript
1
3
1
with open('huge_file') as file:
2
mydict = dict(extract_name_next(file))
3