In Python, you can create a list of dictionaries where each dictionary represents a row of data. This is a common way to represent data when working with Pandas dataframes, as each dictionary represents a single row of data in the dataframe.
Here's an example of how to create a list of dictionaries by row:
# create a list of dictionaries by rowdata = [ {'name': 'John', 'age': 30, 'gender': 'M'}, {'name': 'Jane', 'age': 25, 'gender': 'F'}, {'name': 'Mike', 'age': 35, 'gender': 'M'}, {'name': 'Susan', 'age': 40, 'gender': 'F'}]# loop through the list of dictionaries and print each row of datafor row in data: print(row) |
This will output each row of data as a dictionary:
{'name': 'John', 'age': 30, 'gender': 'M'}{'name': 'Jane', 'age': 25, 'gender': 'F'}{'name': 'Mike', 'age': 35, 'gender': 'M'}{'name': 'Susan', 'age': 40, 'gender': 'F'} |
In this example, the data list contains four dictionaries, each representing a single row of data with the keys name, age, and gender.
You can also add or modify data in a list of dictionaries by row using the dictionary keys:
# add a new row of data to the list of dictionariesdata.append({'name': 'Tom', 'age': 45, 'gender': 'M'})# modify the age of an existing row of datadata[1]['age'] = 30# loop through the updated list of dictionaries and print each row of datafor row in data: print(row) |
This will output the updated list of dictionaries:
{'name': 'John', 'age': 30, 'gender': 'M'}{'name': 'Jane', 'age': 30, 'gender': 'F'}{'name': 'Mike', 'age': 35, 'gender': 'M'}{'name': 'Susan', 'age': 40, 'gender': 'F'}
|
In this example, we added a new row of data to the data list using the append() method, and modified the age of an existing row of data by accessing it with its index and key.