One of my more popular posts is How to Push a Hash on to an Array in PERL, but how do you push a dict on to a list in Python?
Lists are one-dimensional arrays and dicts are associative arrays or hash arrays. This means we can do the same thing we do in other languages, with syntax to match Python’s object-oriented data structures.
import pprint
# Define the list
somelist = []
# Do add some elements to the list
somelist.append({'key1':'value1', 'key2': 'value2'})
somelist.append({'key1':'value1', 'key2': 'value2'})
somelist.append({'key1':'value1', 'key2': 'value2'})
# Print it out
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(somelist)
Will give you:
[Â Â {Â Â 'key1': 'value1', 'key2': 'value2'},
{Â Â 'key1': 'value1', 'key2': 'value2'},
{Â Â 'key1': 'value1', 'key2': 'value2'}]
Did you find this post useful or have questions or comments? Please let me know!