How would you go about extracting part of a key from a dictionary.

I have a text file that lists about 1000 birthdays Ex. 1/2/1980
I want to extract just the year portion from the dictionary and then run a count against each year.
I have no problems with any of it, except how to ignore the 1/2/.

Recommended Answers

All 3 Replies

A couple way is split at / or use a regex.

>>> d = '1/2/2010'.split('/')[2]
>>> d
'2010'

>>> import re
>>> s = re.search(r'\d{4}', '1/2/2010')
>>> s.group()
'2010'
>>>

And for counting from collections module defaultdict(int) (should be capilized but is not) or Counter for latest versions.

Another way

d = '1/2/2010'.split('/')[-1]
'2010'
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.