list + dictionary searching

M

Manoj

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
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

Please give your thoughts

Thanks,
Manoj
 
B

Bruno Desthuilliers

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,900
Latest member
Nell636132

Latest Threads

Top