Mitch
Mitch

Reputation: 177

How can I access elements inside a list within a dictionary python?

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?

Upvotes: 4

Views: 115

Answers (3)

Padraic Cunningham
Padraic Cunningham

Reputation: 180401

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'

Upvotes: 0

Abhijit
Abhijit

Reputation: 63727

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']))
    

Upvotes: 2

JuniorCompressor
JuniorCompressor

Reputation: 20015

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'])

Upvotes: 2

Related Questions