I’ve got a List of stats (extracted from a raw text) structured like this :
list_stats = [u'site1.com', u'3,346', u'23', u'0.68%', u'\u20ac0.04', u'\u20ac0.25', u'\u20ac0.85', u'site2.com', u'45,784', u'243', u'0.56%', u'\u20ac0.34', u'\u20ac0.32', u'\u20ac0.43', u'site3.com', u'9,396', u'432', u'4.54%', u'\u20ac890.24', u'\u20ac9.87', u'\u20ac8.93']
I want to have a Dict like this :
sites = {
u'site1.com' : [u'3,346', u'23', u'0.68%', u'\u20ac0.04', u'\u20ac0.25'],
u'site2.com' : [u'45,784', u'243', u'0.56%', u'\u20ac0.34', u'\u20ac0.32'],
u'site3.com' : [u'9,396', u'432', u'4.54%', u'\u20ac890.24', u'\u20ac9.87', u'\u20ac8.93']
}
So far, I’ve coded this and it’s working :
sites = {}
for field in list_stats:
if 'count' not in locals(): count = 0
if count == 0:
sites[field] = []
current = field
else:
sites[current].append(field)
count = count + 1
if count == 7:
count = 0
However, it doesn’t seem to be perfect. I am sure we can come up with something more clean and elegant. Can your recode it better?
If your version of python supports dict comprehensions (2.7+)
Which, in this case, gives