Search code examples
pythonfiledictionaryfile-read

How to read the first line from a file as key and the next 3 lines as a list of values to a dictionary, python


I'm trying to read a txt that look like:

Animals
Dog
Cat
Bird
Cities
Paris
London
Chicago

into a dictionary. (The first line into a key followed by three lines of values, and so on) It should be looking something like this:

{"Animals":["Dog","Cat","Bird"],"Cities":["Paris","London","Chicago"]

Please help me!


Solution

  • import itertools
    
    d = {}
    
    with open("C:\path\to\text.txt", "r") as f:
        lines = f.readlines()
    
        # Separate keys from values
        keys = itertools.islice(lines, 0, None, 4)
        first_values = itertools.islice(lines, 1, None, 4)
        second_values = itertools.islice(lines, 2, None, 4)
        third_values = itertools.islice(lines, 3, None, 4)
    
        # Set keys and values
        for key in keys:
            key = key.rstrip()
            value1 = first_values.next().rstrip()
            value2 = second_values.next().rstrip()
            value3 = third_values.next().rstrip()
    
            # Create dict
            l = [value1, value2, value3]
            d[key] = l