list + dictionary searching

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Manoj

    list + dictionary searching

    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_utilizati on': 1.0, 'month': 9,
    'user_id': 4, 'year': 2008}, {'username': u'John Wang',
    'user_utilizati on': 1.0, 'month': 10, 'user_id': 4, 'year': 2008},
    {'username': u' ', 'user_utilizati on': 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

  • Bruno Desthuilliers

    #2
    Re: list + dictionary searching

    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_utilizati on': 1.0, 'month': 9,
    'user_id': 4, 'year': 2008}, {'username': u'John Wang',
    'user_utilizati on': 1.0, 'month': 10, 'user_id': 4, 'year': 2008},
    {'username': u' ', 'user_utilizati on': 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(dic t)

    for record in a:
    month_year = "%(month)s_%(ye ar)s" % record
    users[record['user_id']][month_year] = record['user_utilizati on']

    print users.values()

    HTH

    Comment

    • Wojtek Walczak

      #3
      Re: list + dictionary searching

      On Mon, 1 Sep 2008 03:14:22 -0700 (PDT), Manoj wrote:
      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
      Reading about for loop seems like a good idea. You can easily
      create a set of functions that gives you direct access to the
      information you need.




      Give it a try. Try to design some functions that let you
      view and add new lists/dictionaries to your variables.

      --
      Regards,
      Wojtek Walczak,

      Comment

      Working...