identical123456 identical123456 - 1 year ago 69
Python Question

Alternative way to using for loop

Suppose a file looks like this:

abcd 1
abcd 2
abcd 3
xyz 1
xyz 2

My code:

if "abcd" in line:
do something

elif "xyz" in line:
do something

If both "abcd" and "xyz" dynamically change, how would I capture them by writing the same loop?


Can I write a universal loop which counts the number of elements in abcd and xyz? without taking abcd and xyz in its condition.

Answer Source

Not sure I've understood correctly your question, but here's a possible way to gather key & values from your file:

import re
from collections import defaultdict

file = """

abcd      1
abcd       2
abcd        3
xyz        1
xyz       2


output = defaultdict(list)

for line in file.split("\n"):
    if line.strip() == "":

    key, value ='(.*?)\s+(.*)', line).groups()


for k, v in output.iteritems():
    print("{0} has {1} items".format(k, len(v)))