ohid
ohid

Reputation: 914

Return a list of lines as list of tuple with formatting the value with $

def format_Dollar_sign(list):

    lines=['book, 400.2\n', 'pen, 5\n', 'food,  200.5\n', 'gas, 20\n', 'food, 100\n', 'pen, 10\n', 'insurance, 171.35\n', 'gas, 35\n', 'book, 100\n', 'pen, 12\n', 'food, 320\n', 'gas,23.55\n', 'insurance, 110.25']

    #t=[]
    l1 = []
    l2 = []
    for line in lines:
        #l=[]
        parline =line[:-1]
        l1.append(parline)
        t = tuple(l1)
        l2.append(t)

        l1=[]
    L='[' + ', '.join('({})'.format(t[0]) for t in sorted(l2)) + ']'
    return L

print(format_Dollar_sign(list))

This code give me output as: [(book,100),(book,400.2),(food, 200.5)...]

But I am looking output as: [('book','$500.20'),('food', '$200.50')...]

The values are strings which start with a $ and they have two digits of accuracy after the decimal point. Moreover item names are sorted.

Could somebody suggest ways to solve this problem.

Upvotes: 1

Views: 78

Answers (2)

ohid
ohid

Reputation: 914

I solve this problem as follows:

def format_Dollar_sign(list):

    lines=['book, 400.2\n', 'pen, 5\n', 'food,  200.5\n', 'gas, 20\n', 
            'food, 100\n', 'pen, 10\n', 'insurance, 171.35\n', 'gas, 35\n', 
            'book, 100\n', 'pen, 12\n', 'food, 320\n', 
            'gas,23.55\n', 'insurance, 110.25']

    my_dictionary = {}
    for line in lines:
        item, price= line.strip().split(',')

        my_dictionary[item.strip()] = my_dictionary.get(item.strip(),0) + float(price)

    dic={}
    for k,v in my_dictionary.items():
        dic[k]='${0:.2f}'.format(round(v,2))

    L=([(k,v) for k, v in dic.iteritems()])
    L.sort()

    return L
print(format_Dollar_sign(list))

Upvotes: 1

Igor
Igor

Reputation: 1292

The locale module from the standard library takes care of this well. Here is one way to do it which gives your desired output:

import locale


locale.setlocale(locale.LC_ALL, '')
lines=['book, 400.2\n', 'pen, 5\n', 'food,  200.5\n', 'gas, 20\n',
       'food, 100\n', 'pen, 10\n', 'insurance, 171.35\n', 'gas, 35\n',
       'book, 100\n', 'pen, 12\n', 'food, 320\n', 'gas,23.55\n',
       'insurance, 110.25']
itemTupleList = []

for i in lines:
    item = i.split(',')[0]

    # Here I am selecting price, ignoring new line characters, 
    # stripping leading/trailing spaces, converting string to float
    # and finally formatting.
    price = locale.currency(float(i.split(',')[1][:-1].strip()))

    itemTupleList.append((item, price))

print(sorted(itemTupleList))

This and other currency formatting solutions are discussed in this question: Currency formatting in Python

Upvotes: 0

Related Questions