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