creating a dictionary from a dictionary with regex

Discussion in 'Python' started by james_027, Aug 22, 2007.

  1. james_027

    james_027 Guest

    Hi,

    I am trying to create a dictionary from a dictionary which the help of
    regex to identify which keys to select. I have something like this but
    I feel its long and not the fastest solution ... could someone
    contribute?

    import re

    d= {'line2.qty':2, 'line3.qty':1, 'line5.qty':12, 'line2.item':'5c-BL
    Battery', 'line3.item':'N73', 'line5.item':'Screen Cover'}

    collected = [k[:5] for k in d if re.match('^line\d+\.qty',k)]

    for i in collected:
    d2 = {}
    for k in d:
    if re.match('^%s\.\D+' % i, k):
    d2[k] = d[k]
    print d2

    Thanks
    james
     
    james_027, Aug 22, 2007
    #1
    1. Advertising

  2. On Wed, 22 Aug 2007 07:13:40 +0000, james_027 wrote:

    > I am trying to create a dictionary from a dictionary which the help of
    > regex to identify which keys to select. I have something like this but
    > I feel its long and not the fastest solution ... could someone
    > contribute?
    >
    > import re
    >
    > d= {'line2.qty':2, 'line3.qty':1, 'line5.qty':12, 'line2.item':'5c-BL
    > Battery', 'line3.item':'N73', 'line5.item':'Screen Cover'}
    >
    > collected = [k[:5] for k in d if re.match('^line\d+\.qty',k)]
    >
    > for i in collected:
    > d2 = {}
    > for k in d:
    > if re.match('^%s\.\D+' % i, k):
    > d2[k] = d[k]
    > print d2


    You are iterating over `d` for every item in `collected`. With another
    `dict` to store the results you can iterate over `d` only once:

    from collections import defaultdict

    def main():
    d= {'line2.qty':2, 'line3.qty':1, 'line5.qty':12,
    'line2.item':'5c-BL Battery', 'line3.item':'N73',
    'line5.item':'Screen Cover'}

    result = defaultdict(dict)
    for key, value in d.iteritems():
    new_key = key.split('.', 1)[0] # Get the 'line#' part.
    result[new_key][key] = value
    print result

    Ciao,
    Marc 'BlackJack' Rintsch
     
    Marc 'BlackJack' Rintsch, Aug 22, 2007
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Ilias Lazaridis
    Replies:
    6
    Views:
    462
    Ilias Lazaridis
    Feb 21, 2006
  2. Replies:
    3
    Views:
    808
    Reedick, Andrew
    Jul 1, 2008
  3. Navkirat Singh
    Replies:
    6
    Views:
    3,252
    Navkirat Singh
    Jul 29, 2010
  4. Chris Rebert
    Replies:
    0
    Views:
    558
    Chris Rebert
    Jul 29, 2010
  5. Fox

    dictionary within dictionary

    Fox, Mar 8, 2005, in forum: ASP General
    Replies:
    5
    Views:
    203
    Michael D. Kersey
    Mar 13, 2005
Loading...

Share This Page