Python Forum

Full Version: Python dictionary adds only the last elements of a list
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am trying to insert the data values from column_names '<class list>' and stock_data '<class list>' into a dicitonary. When I run the program it loops on all of the data and it only stores that last values of the stock_data. How can I add the entire list values to the data_dict?

	import pandas as pd

	def main():
		
		data = pd.read_json("/home/mahmoud/Desktop/FB.json", orient='records')

    		company_name = data['dataset']['name']
    		columns_names = data['dataset']['column_names']
    		stock_data = data['dataset']['data']

    		data_dict = {}

    		for rows in range(len(stock_data)):
        		for columns in range(12):
            			dataValues = {column_name[columns]:stock_data[rows][columns]}


    		for val in dataValues:
        		print(val, dataValues[val])

	if __name__ == '__main__':main()
Use python tags for multi-line code. The icode tags are for inline code.

You are creating a new dictionary each time through the loop. Create one dictionary before the loop, and update it each time through:

        dataValues = {}
        for rows in range(len(stock_data)):
            for columns in range(12):
                    dataValues[column_name[columns]] = stock_data[rows][columns]