There's nothing wrong with the solution you have come with, but if you want an alternative, regex might come in handy here:
In [10]: import re
In [11]: data = """
...: 41:n
...: 43:n
...: 44:n
...: 46:n
...: 47:n
...: 49:n
...: 50:n
...: 51:n
...: 52:n
...: 53:n
...: 54:n
...: 55:cm
...: 56:n
...: 57:n
...: 58:n"""
In [12]: dict(re.findall(r'(\d+):(.*)', data))
Out[12]:
{'41': 'n',
'43': 'n',
'44': 'n',
'46': 'n',
'47': 'n',
'49': 'n',
'50': 'n',
'51': 'n',
'52': 'n',
'53': 'n',
'54': 'n',
'55': 'cm',
'56': 'n',
'57': 'n',
'58': 'n'}
Explanation:
1st Capturing Group (\d+)
:
\d+
- matches a digit (equal to [0-9])
+
Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)
:
matches the character :
literally (case sensitive)
2nd Capturing Group (.*)
:
.*
matches any character (except for line terminators)
*
Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)
If there might be letters in the first matching group (though I doubt it since your casting that to an int
), you might want to use:
dict(re.findall(r'(.*):(.*)', data))
I usually prefer using split()
s over regex
es because I feel like I have more control over the functionality of the code.
You might ask, why would you want to use the more complicated and verbose syntax of regular expressions rather than the more intuitive and simple string methods? Sometimes, the advantage is that regular expressions offer far more flexibility.
Regarding the comment of @Rahul regarding speed I'd say it depends:
Although string manipulation will usually be somewhat faster, the actual performance heavily depends on a number of factors, including:
- How many times you parse the regex
- How cleverly you write your string code
- Whether the regex is precompiled
As the regex gets more complicated, it will take much more effort and complexity to write equivlent string manipulation code that performs well.
As far as I can tell, string operations will almost always beat regular expressions. But the more complex it gets, the harder it will be that string operations can keep up not only in performance matters but also regarding maintenance.