list + dictionary searching

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Mon Sep 1 06:43:45 EDT 2008


Manoj a écrit :
> Hello All,
> 
> I am very new to python. Any help will be highly appreciated. Thanks
> 
> I have a list of dictionaries:
> 
> a = [{'username': u'John Wang', 'user_utilization': 1.0, 'month': 9,
> 'user_id': 4, 'year': 2008}, {'username': u'John Wang',
> 'user_utilization': 1.0, 'month': 10, 'user_id': 4, 'year': 2008},
> {'username': u' ', 'user_utilization': 1.0, 'month': 9, 'user_id': 1,
> 'year': 2008}]
> 
> I would like to :
> 
> search dictionaries within this list

Care to elaborate ???

> create a new list with dictionaries which gives 1 dictionary for every
> user with month_year as a key and utilization for that month as a
> value

assuming the user_id/month/year combination is unique:

from collections import defaultdict
users = defaultdict(dict)

for record in a:
     month_year = "%(month)s_%(year)s" % record
     users[record['user_id']][month_year] = record['user_utilization']

print users.values()

HTH



More information about the Python-list mailing list