Python Forum
Python dictionary adds only the last elements of a list
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python dictionary adds only the last elements of a list
#1
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()
Reply
#2
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]
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Join each list elements with string in other DF handy88 0 1,519 Feb-09-2021, 07:00 PM
Last Post: handy88
  Formula with elements of list - If-condition regarding the lists elements lewielewis 2 2,702 May-08-2020, 01:41 PM
Last Post: nnk
  Adding a string value to a dictionary that is inside a list mahmoud899 1 2,381 Dec-15-2018, 02:31 PM
Last Post: ichabod801
  Index in Python list contains multiple elements.How to access each val and pass them Shameendra 1 2,388 Nov-30-2018, 05:41 PM
Last Post: wavic
  Checking the elements of a matrix with an elements of a list juniorcoder 11 5,754 Sep-17-2018, 03:02 PM
Last Post: gruntfutuk

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020