change a text file to a dictionary

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • zirkon
    New Member
    • May 2006
    • 1

    change a text file to a dictionary

    I have a text file, which contains a list of element and their weight, and i need to split the list up and sort it by the weight of the elements. So i need
    to change the weight to a float.

    The text file:
    Ac 227.0
    Ag 107.868
    Al 26.98154
    Am 241.1
    Ar 39.948
    As 74.9216
    ...

    So far i have done this:
    Code:
    # ----The data structure----
    # The input file
    text_file=open("avikt.txt","r")  
    Lines = text_file.readlines()    
    text_file.close()
    # The Lines get broken into columns and in 1 list "Element"
    Element = map(string.split,Lines) # now Element is a nested list ...
                                                  # [['Ac','227.0'],['Ag','107.868'],...
    
    # The problem now is to change the atom weight into a float
    # to sort it.
    
    # I make the Element list into a dictionary
    # where the Atom is the key and the atom weight
    # is the value
    d  = dict(Element)
    
    # now i have to sort the dictionary by the value, or the atom weight
    items = [(v,k) for k, v in d.items()]
    items.sort()
    items = [(k,v) for v, k in items]
    Can anybody help me??
    Last edited by bartonc; Apr 7 '07, 05:37 AM. Reason: added [code][/code] tags
  • bartonc
    Recognized Expert Expert
    • Sep 2006
    • 6478

    #2
    Hey, guys...

    This is an old post, but has been viewed over 500 times.
    That's over 500 people looking for an answer, and if they had found one, may have joined the forum. I'll dig up old posts from time to time just for this reason.

    Originally posted by zirkon
    I have a text file, which contains a list of element and their weight, and i need to split the list up and sort it by the weight of the elements. So i need
    to change the weight to a float.

    The text file:
    Ac 227.0
    Ag 107.868
    Al 26.98154
    Am 241.1
    Ar 39.948
    As 74.9216
    ...

    So far i have done this:
    Code:
    # ----The data structure----
    # The input file
    text_file=open("avikt.txt","r")  
    Lines = text_file.readlines()    
    text_file.close()
    # The Lines get broken into columns and in 1 list "Element"
    Element = map(string.split, Lines) # now Element is a nested list ...
                                                  # [['Ac','227.0'],['Ag','107.868'],...
    
    # The problem now is to change the atom weight into a float
    # to sort it.
    
    # I make the Element list into a dictionary
    # where the Atom is the key and the atom weight
    # is the value
    d  = dict(Element)
    
    # now i have to sort the dictionary by the value, or the atom weight
    items = [(v,k) for k, v in d.items()]
    items.sort()
    items = [(k,v) for v, k in items]
    Can anybody help me??
    Sorting a dictionary doesn't work (they are not ordered lists). The use of map() is quite good though.

    Comment

    • ghostdog74
      Recognized Expert Contributor
      • Apr 2006
      • 511

      #3
      one example, although the format of the float values may not be what OP wants
      Code:
      import operator
      data = open("file").readlines()
      data = [i.split() for i in data]
      data = [ [k[0],float(k[1]) ] for k in data]
      data = sorted(data, key=operator.itemgetter(1)) #sort by 2nd element
      data = [ [j[0],"%.5f" % j[1]]  for j in data]
      print data
      output
      Code:
      [['Al', '26.98154'], ['Ar', '39.94800'], ['As', '74.92160'], ['Ag', '107.86800'], ['Ac', '227.00000'], ['Am', '241.10000']]

      Comment

      • bartonc
        Recognized Expert Expert
        • Sep 2006
        • 6478

        #4
        Originally posted by ghostdog74
        one example, although the format of the float values may not be what OP wants
        Code:
        import operator
        data = open("file").readlines()
        data = [i.split() for i in data]
        data = [ [k[0],float(k[1]) ] for k in data]
        data = sorted(data, key=operator.itemgetter(1)) #sort by 2nd element
        data = [ [j[0],"%.5f" % j[1]]  for j in data]
        print data
        output
        Code:
        [['Al', '26.98154'], ['Ar', '39.94800'], ['As', '74.92160'], ['Ag', '107.86800'], ['Ac', '227.00000'], ['Am', '241.10000']]
        You are THE MAN, GD. It makes me wish that I weren't so busy creating GUI apps. I'd love to know the Global Module Index the way that you do (I've never even looked at the operator module before).

        Thanks!

        Comment

        • ghostdog74
          Recognized Expert Contributor
          • Apr 2006
          • 511

          #5
          hi, if you are interested, here's the documentedlink that i got it from.

          Comment

          • bvdet
            Recognized Expert Specialist
            • Oct 2006
            • 2851

            #6
            Nice solution ghostdog74. Like Barton, I am not very familar with the operator module other than to access new division (operator.trued iv()). For the exercise, here's another approach:
            Code:
            data = [item.split() for item in open('file_name').readlines()]
            dataDict = dict(zip([float(i[1]) for i in data], [j[0] for j in data]))
            print dataDict
            
            outList = [[dataDict[key], '%01.5f' % key] for key in sorted(dataDict.keys())]
            print outList
            
            '''
            >>> {39.948: 'Ar', 227.0: 'Ac', 241.09999999999999: 'Am', 26.981539999999999: 'Al', 74.921599999999998: 'As', 107.86799999999999: 'Ag'}
            [['Al', '26.98154'], ['Ar', '39.94800'], ['As', '74.92160'], ['Ag', '107.86800'], ['Ac', '227.00000'], ['Am', '241.10000']]
            >>> 
            '''
            I looked up operator.itemge tter(item):
            'Creates a callable object, f, where a call to f(obj) returns obj[item].'

            Comment

            Working...