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

Viewed 769

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.

3 Answers

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']

Maybe you should use dictionary

 data = {0:[...], 1:[...], ...}

and then you can use

data[indent].append(i) 

so it will works with any indentation and you will no need all these if.

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

data = {}

for line in text.split('\n'):
    striped = line.lstrip()
    indent = len(line) - len(striped)

    # create empty list if not exists
    if indent not in data:
        data[indent] = []

    # add to list
    data[indent].append(striped)

#print(data)

for key, value in data.items():
    print(key, value)

Result:

0 ['Animals', 'Birds', 'Reptiles', 'Mammals']
2 ['Tiger', 'Lion', 'Parrot', 'Peacock']
4 ['Cat', 'Hen']
6 ['Mice', 'chicken']

In dynamic programming you should use dictionary and list instead of separated variables a, b, c, d. Eventually you could use dictinary with string keys "a", "b", "c", "d" but you can always convert values 0, 2, 4 to chars a, b, c

for key, value in data.items():
    char = chr(ord('a') + key//2)
    print(char, value)

Result

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

You can try the following, using a dictionary with length of indentation as keys:

d={}

def categ(x):
    n=0
    i=0
    while x[i]==' ':
        n+=1
        i+=1
    return n

for i in text:
    if categ(i) in d:
        d[categ(i)].append(i[categ(i):])
    else:
        d[categ(i)]=[i[categ(i):]]
Related