Python Forum
Help accessing elements of list of dictionaries
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help accessing elements of list of dictionaries
#1
I have filled a list with dictionaries in the following code. I have watched at least 5 videos looking for the answer. How can I access elements of individual dictionaries residing within that list?

def load_racefiles() :

	count = 0
	master_race_file = []
	rows = 100
	columns = 100
	horse_array = [0 for i in range(rows)] 
	file_name = StringVar()
	f_name = StringVar()
	#file_dir = (r"C:\2020")
	fd =    open("dirpath", "r") 
	file_dir = (fd.read())
	fd.close()
	os.chdir(file_dir)
	for f in os.listdir(file_dir): 
		file_name, file_ext = os.path.splitext(f)
		f_name = file_name + file_ext
		file_name = file_name.strip()[3:]
		line_counter = 0
		if file_name == Race_date and file_ext == ".jcp":
			with open(f_name, "r") as csv_file:
				csv_reader = csv.reader(csv_file)
				
				for line in csv_reader:
					
											

				
					
					h = {'track' : line[0],
					'race_number' : line[2], 
					'todays_surface' : line[6],
					'race_type' : line[8], 
					'todays_purse' : line[11],
					'trn_starts_curmeet' : line[28],
					'trn_wins_curmeet' : line[29],
					'jock_sts_curmeet' : line[34],
					'jock_wins_curmeet' : line[35],
					'trn_starts_prevyear' : line[1151],
					'trn_wins_prevyear' : line[1152],
					'jock_sts_prevyear' : line[1161],
					'jock_wins_prevyear' : line[1162],
					'trn_starts_curyear' : line[1146],
					'trn_wins_curyear' : line[1147],
					'jock_sts_curyear' :  line[1156],
					'jock_wins_curyear':  line[1157],
					'morn_line': line[43],
					'horse_name' : line[44],
					'year_of_birth' : line[45],
					'hstarts_todays_dist' : line[64],
					'hwins_todays_dist ' : line[65],
					'hstarts_todays_track' : line[69],
					'hwins_todays_track' :line[70],
					'hstarts_turf' : line[74],
					'hwins_turf' : line[75],
					'hstarts_mud' : line[79],
					'hwins_mud' : line[80],
					'hstarts_cur_yr' : line[84],
					'hwins_cur_yr' : line[85],
					'hstarts_prev_yr' : line[90],
					'hwins_prev_yr' : line[91],
					'hstarts_life' : line[96],
					'hwins_life' : line[97], 
					'days_since' : line[223],
					'power_rating' : line[250],
					'dist_yards1' : line[315],
					'dist_yards2' : line[316],
					'dist_yards3' : line[317],
					'dist_yards4' : line[318],
					'dist_yards5' : line[319],
					'dist_yards6' : line[320],
					'dist_yards7' : line[321],
					'dist_yards8' : line[322],
					'dist_yards9' : line[323],
					'dist_yards10' : line[324],
					'surface1' : line[325],
					'surface2' : line[326],
					'surface3' : line[327],
					'surface4' : line[328],
					'surface5' : line[329],
					'surface6' : line[330],
					'surface7' : line[321],
					'surface8' : line[332], 
					'surface9' : line[333],
					'surface10' : line[334],
					'entrants1' : line[345],
					'entrants2' : line[346],
					'entrants3' : line[347],
					'entrants4' : line[348],
					'entrants5' : line[349],
					'entrants6' : line[350],
					'entrants7' : line[351],
					'entrants8' : line[352],
					'entrants9' : line[353],
					'entrants10' : line[354],
					'first_call1' :  line[575],
					'first_call2' : line[576],
					'first_call3' : line[577],
					'first_call4' : line[578],
					'first_call5' : line[579],
					'first_call6' : line[580],
					'first_call7' : line[581],
					'first_call8' : line[582],
					'first_call9' : line[583],
					'first_call10' : line[584],
					'second_call1' : line[585],
					'second_call2' : line[586],
					'second_call3' : line[587],
					'second_call4' : line[588],
					'second_call5' : line[589],
					'second_call6' : line[590],
					'second_call7' : line[591],
					'second_call8' : line[592],
					'second_call9' : line[593],
					'second_call0' : line[594],
					'finish_Position' : line[615],
					'last_peed' : line[845],
					'speed_2back' : line[846],
					'speed_3back' : line[847],
					'bestSpeed_Life' : line[1327],
					'bestSpeed_Fasttrack' : line[1177],
					'bestSpeed_turf' : line[1178],
					'bestSpeed_offtrack' : line[1179],
					'bestSpeed_dist' : line[1180],
					'race_conditions' : line[15],
					'todays_race_classification' : line[10]

					

 				
 						}

					master_race_file.append(h ) 
Reply
#2
If you have a list of dictionaries, you access by giving the list index first, then the dictionary key.

list_of_dicts = [{'a': 1,
                  'b': 2,
                  'c': 3,
                 },
                 {'a': 4,
                  'b': 5,
                  'c': 6,
                 },
                 {'a': 7,
                  'b': 8,
                  'c': 9,
                 },
                ]
print(list_of_dicts[0]['b'])  # first list element, dict key 'b'
print(list_of_dicts[2]['b'])  # third list element, dict key 'b'
Output:
2 8
Reply
#3
Thank you. I defined the list master_race_file = [] in function load_racefiles() . How do I access the list outside of the function? When I try I get error master_race_file is not defined, or this error

$ python hello2.py
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Milford\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 1883, in __call__
return self.func(*args)
File "hello2.py", line 1279, in load_racefiles
print(master_race_file[0]['horse_name'])
IndexError: list index out of range

Thanks in advance
Reply
#4
Usually you would return the data structure to the calling program. Then the caller would assign it to a variable.

def load_racefiles():
    # calculate master_race_file
    return master_race_file


master_race_file = load_racefiles()
print(master_race_file[0]['horse_name'])
Reply
#5
I changed the code as you suggested. Here is the result... where as before adding your code no error message.


$ python hello2.py
Traceback (most recent call last):
File "hello2.py", line 1283, in <module>
master_race_file = load_racefiles()
File "hello2.py", line 1164, in load_racefiles
if file_name == Race_date and file_ext == ".jcp":
NameError: name 'Race_date' is not defined

I changed the code and put it like this. And it works. But problem is I am still in the load_races function

master_race_file.append(h ) 
			
				my_labeldone= Label( text ="Downloading Complete", fg= "black", font = ("sans_serif" , 16)).place(x=500, y=500)
	print( master_race_file[0]['todays_race_classification'])
I wanted to access the info outside the function.
Reply
#6
Do you understand the snippet I posted? The error you have shown now isn't related. However, it's not feasible for us to try to debug a 1200+ line program. You should try to cut it down to a much simpler example that shows your problem that others can run.
Reply
#7
Ok. Hopefully this will be better.

my_button1 = Button(root, text = "Load Race Files", width = 15, command = load_racefiles) 
my_button1.place(x=443, y=150)

def load_racefiles() :
	global Race_date

	count = 0
	master_race_file = []
	rows = 100
	columns = 100
	horse_array = [0 for i in range(rows)] 
	file_name = StringVar()
	f_name = StringVar()
	
	fd =    open("dirpath", "r") 
	file_dir = (fd.read())
	fd.close()
	os.chdir(file_dir)
	for f in os.listdir(file_dir): 
		file_name, file_ext = os.path.splitext(f)
		f_name = file_name + file_ext
		file_name = file_name.strip()[3:]
		line_counter = 0
		if file_name == Race_date and file_ext == ".jcp":
			with open(f_name, "r") as csv_file:
				csv_reader = csv.reader(csv_file)
				
				for line in csv_reader:

                     h = {'track' : line[0],
                     'horse_name' : line[44]
                          }
                    master_race_file.append(h ) 
					
				my_labeldone= Label( text ="Downloading Complete", fg= "black", font = ("sans_serif" , 16)).place(x=500, y=500)
This all works. Now I need to access the dictionaries to see if the track name and the race date selected by the user previous to load_files function is called are equal so I can put that line in a separate smaller list so I can then manipulate the data.

I hope this is easier to deal with.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  unable to remove all elements from list based on a condition sg_python 3 442 Jan-27-2024, 04:03 PM
Last Post: deanhystad
  Sort a list of dictionaries by the only dictionary key Calab 1 490 Oct-27-2023, 03:03 PM
Last Post: buran
Question mypy unable to analyse types of tuple elements in a list comprehension tomciodev 1 480 Oct-17-2023, 09:46 AM
Last Post: tomciodev
  Access list of dictionaries britesc 4 1,073 Jul-26-2023, 05:00 AM
Last Post: Pedroski55
  Checking if a string contains all or any elements of a list k1llcod3 1 1,102 Jan-29-2023, 04:34 AM
Last Post: deanhystad
  How to change the datatype of list elements? mHosseinDS86 9 1,996 Aug-24-2022, 05:26 PM
Last Post: deanhystad
  ValueError: Length mismatch: Expected axis has 8 elements, new values have 1 elements ilknurg 1 5,137 May-17-2022, 11:38 AM
Last Post: Larz60+
  Why am I getting list elements < 0 ? Mark17 8 3,132 Aug-26-2021, 09:31 AM
Last Post: naughtyCat
  Looping through nested elements and updating the original list Alex_James 3 2,127 Aug-19-2021, 12:05 PM
Last Post: Alex_James
  Extracting Elements From A Website List knight2000 2 2,267 Jul-20-2021, 10:38 AM
Last Post: knight2000

Forum Jump:

User Panel Messages

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