I want to print a dictionary inside a list like this :
[{name : 'red', id : '1'}, {name : 'yellow', id : '2'}, {name : 'black', id : '3'}, {name : 'white', id : '4'}]`
I don't want quotations in name
and id
. However, I want them in the values portion of that dictionary.
Dictionaries can be contained in lists and vice versa.
Use the copy() method to create a shallow copy of the dictionary. Use the list. append() method to append the copy to the list. The list will contain the dictionary by value, and not by reference.
A Python list can contain a dictionary as a list item.
You'd have to write your own formatting function to do that.
Here's a hairy but terse function that does what you want:
def pretty_print(data):
return '[%s]' % ', '.join(
'{%s}' % ', '.join(
'%s : %r' % (key, value) for key, value in item.items()
) for item in data
)
So the following code:
print(pretty_print([
{'name': 'red', 'id': '1'},
{'name': 'yellow', 'id': '2'},
]))
Would print:
[{name : 'red', id : '1'}, {name : 'yellow', id : '2'}]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With