Thread: Simplify!

    #1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2004
    Location
    Bombay, India
    Posts
    159
    Rep Power
    13

    Simplify!


    Hi,
    Can anyone simplify this code.....very simple one!

    >>> d1
    {'a': 1, 'b': 2}
    >>> d2
    {'a': 20, 'p': 40, 'r': 60, 'b': 30, 'q': 50}
    These are my two dictionaries.... they are the nodes actually containing attributes.

    >>> temp={}
    >>> child_avs={}
    >>> for (k,v) in d1.items():
    ... for (k1,v1) in d2.items():
    ... if k==k1:
    ... temp={k:v1}
    ... child_avs.update(temp)
    ...
    >>> child_avs
    {'a': 20, 'b': 30}
    I'm trying to replace the keys of d1...which is my child...to contain the values in d2.... simply put as

    d1={'a':1,'b':'2'}
    d2={'a': 20, 'p': 40, 'r': 60, 'b': 30, 'q': 50}

    finally I want d1={'a':20,'b':30}

    Thats all!

    Thanks,
    Subha
  2. #2
  3. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2003
    Posts
    206
    Rep Power
    12
    Is that what you want?

    Code:
    >>> d1 =  {'a': 1, 'b': 2}
    >>> d2 =  {'a': 20, 'p': 40, 'r': 60, 'b': 30, 'q': 50}
    >>> for key in d2.keys():
    ...   if d1.has_key(key):
    ...     d1[key] = d2[key]
    ...
    >>> d1
    {'a': 20, 'b': 30}
    >>>
  4. #3
  5. Mini me.
    Devshed Novice (500 - 999 posts)

    Join Date
    Nov 2003
    Location
    Cambridge, UK
    Posts
    783
    Rep Power
    14
    Code:
    for n in d1: d1[n]=d2[n]
    grimey
  6. #4
  7. Mini me.
    Devshed Novice (500 - 999 posts)

    Join Date
    Nov 2003
    Location
    Cambridge, UK
    Posts
    783
    Rep Power
    14
    Improved....
    Code:
    for n in d1: d1[n] = d2.get(n,d1[n])
    on the assumption that keys not being in d2 is a rare situation

    grim
    Last edited by Grim Archon; December 20th, 2004 at 06:52 AM.
  8. #5
  9. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2004
    Location
    Bombay, India
    Posts
    159
    Rep Power
    13
    Hey,
    Thanks Wiz for that solution!

    Grim, your solution was mind-blowing...n the last one was even more....n since now I've blown my mind...could I get your brains hehehehe


    Thanks,
    Subha

IMN logo majestic logo threadwatch logo seochat tools logo