Search code examples
pythonlistdictionarysplice

getting data out of a list of dict's with same names eg. [{route number : 123,}, {happy customers : 1.5}, {route number : 456}, {happy customers : 0}]


i am having a bit of trouble with this not sure of best way to go

objective = import csv from file, convert to list of dict, get user input (number), print (number) of values from key. csv is a .txt file example input in .txt file is: (routes.txt) below is in this file

route number, happy customers
123,4
321,0
789,6.7001

i can convert data to a list of dicts using the following

number = input("please enter number of spare busses that can be assigned to routes: ")

    if (os.path.exists("routes.txt")) == True:
    with open("routes.txt", "r") as in_file:
        list_dict = csv.DictReader(in_file,delimiter = ",")
        list_dict = list(list_dict)
        print(list_dict)
##### output = [{'Route number': '123', 'Happy customers': '4'}, {'Route number': '321', 'Happy customers': '0'}, {'Route number' : '789', 'Happy customers': '6.7001'}]

else:
    print("The File routes.txt can not be found, please ensure the file is in the current working directory.")

however i can't seem to find a way to get the (number) printed out number is from user input and need to print that (number) only of route numbers from list of dict after the list has been sorted only thing that i found comes close is enumerate to new nested dict but i dont know how to get data from that. any help pointing in right direction would be appreciated.


Solution

  •  rec_routes = [route["route number"] for route in sorted_list]
    

    found this to convert all route numbers in the list of dictionaries to a list of route numbers after they had been sorted.