简体   繁体   中英

List of dictionaries - how to format print output

I have a list of dictionaries:

lis = [{'score': 7, 'numrep': 0}, {'score': 2, 'numrep': 0}, {'score': 9, 'numrep': 0}, {'score': 2, 'numrep': 0}] 

How can I format the output of a print function:

print(lis)

so I would get something like:

[{7-0}, {2-0}, {9-0}, {2-0}]

A list comp will do:

['{{{0[score]}-{0[numrep]}}}'.format(d) for d in lst]

This outputs a list of strings, so with quotes:

['{7-0}', '{2-0}', '{9-0}', '{2-0}']

We can format that a little more:

'[{}]'.format(', '.join(['{{{0[score]}-{0[numrep]}}}'.format(d) for d in lst]))

Demo:

>>> print ['{{{0[score]}-{0[numrep]}}}'.format(d) for d in lst]
['{7-0}', '{2-0}', '{9-0}', '{2-0}']
>>> print '[{}]'.format(', '.join(['{{{0[score]}-{0[numrep]}}}'.format(d) for d in lst]))
[{7-0}, {2-0}, {9-0}, {2-0}]

Alternative methods of formatting the string to avoid the excessive {{ and }} curl brace escaping:

  • using old-style % formatting:

     '{%(score)s-%(numrep)s}' % d 
  • using a string.Template() object:

     from string import Template f = Template('{$score-$numrep}') f.substitute(d) 

Further demos:

>>> print '[{}]'.format(', '.join(['{%(score)s-%(numrep)s}' % d for d in lst]))
[{7-0}, {2-0}, {9-0}, {2-0}]
>>> from string import Template
>>> f = Template('{$score-$numrep}')
>>> print '[{}]'.format(', '.join([f.substitute(d) for d in lst]))
[{7-0}, {2-0}, {9-0}, {2-0}]
l = [ 
  {'score': 7, 'numrep': 0}, 
  {'score': 2, 'numrep': 0}, 
  {'score': 9, 'numrep': 0}, 
  {'score': 2, 'numrep': 0}
]

keys = ['score', 'numrep']
print ",".join([ '{ %d-%d }' % tuple(ll[k] for k in keys) for ll in l ])

Output:

{ 7-0 },{ 2-0 },{ 9-0 },{ 2-0 }

You can use a list comprehension and string formatting :

>>> lis = [{'score': 7, 'numrep': 0}, {'score': 2, 'numrep': 0}, {'score': 9, 'numrep': 0}, {'score': 2, 'numrep': 0}] 
>>> ["{{{score}-{numrep}}}".format(**dic) for dic in lis]
['{7-0}', '{2-0}', '{9-0}', '{2-0}']

New-style formatting requires {{}} to escape a {} , so it's a bit less readable for this case. Another alternative is string.Template , it allows $ as place-holders for keys so the solution is much more readable in this case.:

>>> from string import Template
>>> s = Template('{$score-$numrep}')
>>> [s.substitute(dic) for dic in lis]
['{7-0}', '{2-0}', '{9-0}', '{2-0}']

If instead list of strings you need a single string, then try this:

>>> from string import Template
>>> s = Template('{$score-$numrep}')
>>> print '[{}]'.format(', '.join(s.substitute(dic) for dic in lis))
[{7-0}, {2-0}, {9-0}, {2-0}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM