Search code examples
pythonpython-3.xlistdictionaryindentation

How to create list dynamically based on different conditions in python?


Text file:

Animals
  Tiger
  Lion
    Cat
      Mice
Birds
  Parrot
  Peacock
    Hen
      chicken
Reptiles
Mammals

I want to dynamically separate the words based on the indentation and store it in a different lists

Expected Output:

a=['Animals','Birds','Reptiles','Mammals']
b=['Tiger','Lion','Parrot','Peacock']
c=['Cat','Hen']
d=['Mice','Chicken']

Here is my code:

a=[]
b=[]
c=[]
d=[]
for i in text:
  indent = len(i)-len(i.lstrip())
  if indent == 0:
    a.append(i)
  if indent == 2:
    b.append(i)
  if indent == 4:
    c.append(i)
  if indent == 6:
    d.append(i)        

It gives the expected output but I want it in dynamic approach.


Solution

  • You can use defaultdict:

    from collections import defaultdict
    data = defaultdict(list)
    with open('test.txt') as f:
        for line in f:
            indentation_level = (len(line) - len(line.lstrip())) // 2
            data[indentation_level].append(line.strip())
    
    for indent_level, values in data.items():
        print(indent_level, values)
    
    0 ['Animals', 'Birds', 'Reptiles', 'Mammals']
    1 ['Tiger', 'Lion', 'Parrot', 'Peacock']
    2 ['Cat', 'Hen']
    3 ['Mice', 'chicken']