Search code examples
pythonpython-3.xdictionarystring-formatting

Remove specific strings from a dictionary


I have a dictionary which is in this format

Open = {'22.0x7.5x8.0 12.0': ['4.60x4.30x4.30 13.00, 4.60x4.30x4.30 1.00, 
                              4.60x4.30x4.30 2.00, 6.60x6.00x5.16 5.00'], 
         '18.0x7.0x7.0 7.0': ['4.60x4.30x4.30 1.00, 8.75x6.60x5.60 4.00'],
           '22.0x7.5x8.0 9.0': ['6.60x6.00x5.16 5.00, 6.60x6.00x5.16 9.00, 
                                6.60x6.00x5.16 5.00']}

I want to remove the dimensions part(1x2x3) from keys as well as values and convert the remaining part in integer. How can I do that ?

such that my output is like this

new = {12:[13,1,2,5],
          7:[1,4]...}

Solution

  • Using str.split should be enough.

    Open = {'22.0x7.5x8.0 12.0': ['4.60x4.30x4.30 13.00, 4.60x4.30x4.30 1.00',
                                  '4.60x4.30x4.30 2.00, 6.60x6.00x5.16 5.00'],
             '18.0x7.0x7.0 7.0': ['4.60x4.30x4.30 1.00, 8.75x6.60x5.60 4.00'],
               '22.0x7.5x8.0 9.0': ['6.60x6.00x5.16 5.00, 6.60x6.00x5.16 9.00',
                                    '6.60x6.00x5.16 5.00']}
    
    res = {}
    for key,value in Open.items():
    
        #Split on space and convert to int for key
        k = int(float(key.split()[1]))
        li = []
        for v in value:
            #First split on comma
            for i in v.split(','):
                #Then split on space
                num = int(float(i.split()[1]))
                #Append the number to a list
                li.append(num)
        #Assign the list to the key
        res[k] = li
    
    print(res)
    

    The output will be

    {12: [13, 1, 2, 5], 7: [1, 4], 9: [5, 9, 5]}