Create dictionary from another dictionary

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • GTXY20
    New Member
    • Oct 2007
    • 29

    Create dictionary from another dictionary

    Hello;

    I have the following dictionary:

    Code:
    d={1:[a,b,b], 2:[a,a,b,c], 3:[a,b,c], 4:[a,c]}
    I am having trouble removing the duplicate values in each of the keys value list, I need it so that:

    [CODE]d={1:[a,b], 2:[a,b,c], 3:[a,b,c], 4:[a,c]}{/CODE]

    I was thinking of that I would need to import the sets module???
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Originally posted by GTXY20
    Hello;

    I have the following dictionary:

    Code:
    d={1:[a,b,b], 2:[a,a,b,c], 3:[a,b,c], 4:[a,c]}
    I am having trouble removing the duplicate values in each of the keys value list, I need it so that:

    Code:
    d={1:[a,b], 2:[a,b,c], 3:[a,b,c], 4:[a,c]}{/CODE]
    
    I was thinking of that I would need to import the sets module???
    Code:
    Are you in Python 2.3? Here is one way of doing it:[code=Python]dd = {1:['a','b','b'], 2:['a','a','b','c'], 3:['a','b','c'], 4:['a','c']}
    
    for item in dd.items():
        # Python 2.3
        dd[item[0]] = [i for i in item[1] if i not in locals()['_[1]'].__self__]
        # Python 2.4
        # dd[item[0]] = [i for i in item[1] if i not in locals()['_[1]']]
    
    print dd
    
    # >>> {1: ['a', 'b'], 2: ['a', 'b', 'c'], 3: ['a', 'b', 'c'], 4: ['a', 'c']}
    If you are in 2.3, import Set from sets like this:[code=Python]>>> from sets import Set as set[/code] ...and it will seem like you are in 2.4.

    Comment

    • GTXY20
      New Member
      • Oct 2007
      • 29

      #3
      Thanks!

      I am actually using PythonWin 2.5.1.

      Will this cause any problems - I am away from my workstation.

      Comment

      • bvdet
        Recognized Expert Specialist
        • Oct 2006
        • 2851

        #4
        Originally posted by GTXY20
        Thanks!

        I am actually using PythonWin 2.5.1.

        Will this cause any problems - I am away from my workstation.
        Not that I am aware of. Try the 2.4 version. If that does not work or if you would prefer using set(), use list(set([a,a,b,c])) instead. set() is built-in - no need to import.

        Comment

        • GTXY20
          New Member
          • Oct 2007
          • 29

          #5
          2.4 version works great!

          Thank you.

          Comment

          Working...