Python Forum
Adding a string value to a dictionary that is inside 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: Adding a string value to a dictionary that is inside a list (/thread-14748.html)



Adding a string value to a dictionary that is inside a list - mahmoud899 - Dec-15-2018

This program prints out the following:
{'Date': '2018-12-11', 'Open': 143.88, 'High': 143.88, 'Low': 141.1, 'Close': 142.08, 'Volume': 20300349.0, 'Dividend': 0.0, 'Split': 1.0, 'Adj_Open': 143.88, 'Adj_High': 143.88, 'Adj_Low': 141.1, 'Adj_Close': 142.08, 'Adj_Volume': 20300349.0}

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']

    # Here is the change
    data_list = [{c: v for c, v in zip(columns_names, r)} for r in stock_data]

    for val in range(len(data_list)):
        print(data_list[val])

if __name__ == '__main__':main()
I would like to make the program to print out:
{'Company Name':company_name(the value of the company_name string), 'Date': '2018-12-11', 'Open': 143.88, 'High': 143.88, 'Low': 141.1, 'Close': 142.08, 'Volume': 20300349.0, 'Dividend': 0.0, 'Split': 1.0, 'Adj_Open': 143.88, 'Adj_High': 143.88, 'Adj_Low': 141.1, 'Adj_Close': 142.08, 'Adj_Volume': 20300349.0}


RE: Adding a string value to a dictionary that is inside a list - ichabod801 - Dec-15-2018

I would change the data comprehension on line 11 into a loop, and add that information in the loop:

data_list = []
for row in stock_data:
    data_list.append({column_name: value for column_name, value in zip(column_names, row)})
    data_list[-1]['Company Name'] = company_name