Skip to content
Advertisement

After a match of a string in a file, how to extract the next set of lines and continue iteration

JavaScript

I want to search for line “Name” and the immediate next line and use it as Key: Value.

Code:-

JavaScript

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

This is a generator function that yields (key, value) pair. To print you can use it like

JavaScript

You could also construct a dict from these pairs:

JavaScript

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
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement