How to create and append dictionary at the same time?
def buildList(theDict):
array=[]
for a,b in theDict.iteritems():
array.append([a,b])
return array
print buildList({"a": 1,"b": 2,"c": 3})
This prints out a list of lists. I want to print out a list of dictionaries without creating any new variables.
If I understand correctly what you want, this code should work.
list_of_dicts()uses a list comprehension, which creates a newdictwith a single entry for each key/value pair in the passed-in dictionary.Do you see how you could use a list comprehension to re-write your example, and return a list of lists? It would just require changing three characters in the above.
P.S. I used PEP 8 names (lower_case rather than camelCase).