Python dictionary adds only the last elements of a list - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Data Science (https://python-forum.io/forum-44.html) +--- Thread: Python dictionary adds only the last elements of a list (/thread-14717.html) |
Python dictionary adds only the last elements of a list - mahmoud899 - Dec-13-2018 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() RE: Python dictionary adds only the last elements of a list - ichabod801 - Dec-13-2018 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] |