How can I access the elements inside a list in a python dictionary?

I have a function that returns a formatted json 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, not a list:

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

What is the most efficient way to do this?

+4
source share
3 answers

Two quick fixes in your code should solve it

  • Attach the list returned trans['category']by comma separated so that it is a string, not a string representation of the list.
  • Enter format specifier for categoryieCategories =\'{}\'

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

You can join category items:

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

and use it instead of printing:

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

dict str.format :

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'
0

Source: https://habr.com/ru/post/1584776/


All Articles