4

I have a function that's returning a json formatted dataset. Here's a sample:

[{u'category': [u'Transfer', u'Withdrawal', u'ATM'], u'category_id': u'21012002', u'_account': u'XARE85EJqKsjxLp6XR8ocg8VakrkXpTXmRdOo', u'name': u'ATM Withdrawal', u'amount': 200, u'meta': {u'location': {u'city': u'San Francisco', u'state': u'CA'}}, u'date': u'2014-07-21', u'score': {u'location': {u'city': 1, u'state': 1}, u'name': 1}, u'_id': u'0AZ0De04KqsreDgVwM1RSRYjyd8yXxSDQ8Zxn', u'type': {u'primary': u'special'}, u'pending': False}] 

for trans in foodie_data:
            print 'Name={},Amount={},Date={}, Categories ={}\n'.format(trans['name'],trans['amount'],trans['date'],trans['category'])

This script prints:

Name=ATM Withdrawal,Amount=200,Date=2014-07-21,Categories=[u'Transfer', u'Withdrawal', u'ATM']

I want it to return Categories as a string and not a list:

Name=ATM Withdrawal,Amount=200,Date=2014-07-21,Categories='Transfer, Withdrawal,ATM']

What's the most efficient way of doing so?

1
  • 1
    ', '.join(trans['category'])? Commented Apr 26, 2015 at 18:55

3 Answers 3

2

Two quick fix in your code should solve it

  1. Join the list returned by trans['category'] separated by comma such that it is a string rather than a string representation of list.
  2. Quote the format specifier for category i.e. Categories =\'{}\'

    for trans in foodie_data:
        print 'Name={},Amount={},Date={}, Categories =\'{}\'\n'.format(
        trans['name'],
        trans['amount'],
        trans['date'],
        ', '.join(trans['category']))
    
Sign up to request clarification or add additional context in comments.

Comments

2

You can join the elements of categories:

>>> categories = [u'Transfer', u'Withdrawal', u'ATM']
>>> ",".join(categories)
u'Transfer,Withdrawal,ATM'

and use it instead when printing your output:

",".join(trans['category'])

Comments

0

You can also you the dict directly with str.format to access the rest of the values:

for trans in foodie_data:
    print "Name={name},Amount={amount},Date={date}," \
       "Categories='{}'\n".format(",".join(trans["category"]),**trans)


 Name=ATM Withdrawal,Amount=200,Date=2014-07-21,Categories='Transfer,Withdrawal,ATM'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.