Re: [Tutor] enumerate over Dictionaries
On 06/07/2019 05:28, Suhit Kumar wrote: > I have made the complete program but when I am compiling the program it is > showing errors. Can you please help to resolve this? > The code is in the file attached with this mail. And where are the errors? Do not expect us to run unknown code received over the internet. Only a fool would do such a thing! Show us the error messages, with full traceback text. A quick scan of the code reveals some stylistic things that you could do but they are not the cause of your errors, whatever they may be: for i,ex in teacher.iterrows(): lat1 = ex['Latitude'] lon1 = ex['Longitude'] Id = i for b,c in df.iterrows(): lat2 = c['latitude'] lon2 = c['longitude'] nameVen = c['name'] listEmpty.append((distanceCalculator(float(lat1), float(lon1),float(lat2),float(lon2)),Id,b)) demian = [] listEmpty.sort() demian = listEmpty[0] dictionaryTeacher[ex['Name']] = demian listEmpty = [] demian = [] listEmpty is a terrible name choice. You should never name variables after their data type name them for the purpose they serve. And don;t call it empty since that only applies at one particular poit. name it after what you intend to store in it... secondly you initialise demian to a list. Then you throw that list away and assign a different value to it. The initial assignment is pointless. You initialise listEmpty outside the loop and then again at the end. If you move the initialisation into the loop body at the top you won't need to reset it at the end. It only saves a line of code but if you ever need to change the initial value it means you only need to do it in one place. I don't have time to read through the rest. You really should refactor your code into functions. It will make it easier to modify, easier to debug, and much easier to read and discuss. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] enumerate over Dictionaries
Hi, I have made the complete program but when I am compiling the program it is showing errors. Can you please help to resolve this? The code is in the file attached with this mail. On Fri, Jul 5, 2019 at 10:44 PM Animesh Bhadra wrote: > Thanks Alan and Mats for the explanation. > > On 05/07/19 19:57, Mats Wichmann wrote: > > On 7/4/19 3:53 PM, Alan Gauld via Tutor wrote: > > > >>> Does this means that the Dict is ordered? or it is implementation > dependent? > >> Neither, it means the items in a list always have indexes > >> starting at zero. > >> > >> By pure coincidence dictionaries in recent Python versions (since 3.6 > >> or 3.7???) retain their insertion order. But that was not always the > >> case, but the result would have been the same so far as the 0,1,2 bit > goes. > >> > > To be a little more precise, in 3.6 CPython insertion order was > > preserved as an artefact of the new implementation of dicts, but not > > promised to be that way. Since 3.7 it is guaranteed (it is actually in > > the language specification, so other Pythons have to do this too now). > > > > It's still not the same as a collections.OrderedDict, which has some > > useful additional features in case you care a lot about ordering. > > > > ___ > > Tutor maillist - Tutor@python.org > > To unsubscribe or change subscription options: > > https://mail.python.org/mailman/listinfo/tutor > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > import math import csv import pdb import pandas as pd import numpy as np from math import radians, sin, cos, acos def distanceCalculator(latitude1,longitude1,latitude2,longitude2): slat = radians(latitude1) slon = radians(longitude1) elat = radians(latitude2) elon = radians(longitude2) dist = 6371.01 * acos(sin(slat)*sin(elat) + cos(slat)*cos(elat)*cos(slon - elon)) return dist df = pd.read_csv("venueData.csv",header=None) df.columns=['name','latitude','longitude','district','block'] df2 = pd.read_csv("mtdata.csv",header=None) df2.columns = ['name','location','latitude','longitude','subject'] teacher = pd.read_csv("teachers.csv") teacher.head() df.head() teacher['Latitude'] = teacher['Latitude'].apply(lambda x: x.rstrip(",") if type(x) == str else x ) teacher['Longitude'] = teacher['Longitude'].apply(lambda x: x.rstrip(",") if type(x) == str else x ) listEmpty = [] dictionaryTeacher = {} for i,ex in teacher.iterrows(): lat1 = ex['Latitude'] lon1 = ex['Longitude'] Id = i for b,c in df.iterrows(): lat2 = c['latitude'] lon2 = c['longitude'] nameVen = c['name'] listEmpty.append((distanceCalculator(float(lat1),float(lon1),float(lat2),float(lon2)),Id,b)) demian = [] listEmpty.sort() demian = listEmpty[0] dictionaryTeacher[ex['Name']] = demian listEmpty = [] demian = [] DataTeacher = pd.DataFrame(columns=['Teacher','Distance','Venue','Eng','Hindi','Maths','TeacherId']) number = 3 for ex in dictionaryTeacher: DataTeacher= DataTeacher.append({'Teacher':ex,'Distance':dictionaryTeacher[ex][0],'Venue':df.loc[dictionaryTeacher[ex][2]]['name'],'Eng':teacher.loc[dictionaryTeacher[ex][1]]['Eng'],'Hindi':teacher.loc[dictionaryTeacher[ex][1]]['Hindi'],'Maths':teacher.loc[dictionaryTeacher[ex][1]]['Maths'],'TeacherId':dictionaryTeacher[ex][1]},ignore_index=True) days = pd.read_csv("days.csv") days.columns = ['January', 'January:Days', 'February', 'Feburary:Days', 'March', 'March:Days', 'April', 'April:Days', 'May', 'May:Days', 'June', 'June:Days', 'July', 'July:Days', 'August', 'August:Days', 'September', 'September:Days', 'October', 'October:Days', 'November', 'November:Days', 'December', 'December:Days'] df.columns=['name','latitude','longitude','district','block'] df['name'] = df['name'].apply(lambda x: x.rstrip()) df2['name'] =df2['name'].apply(lambda x: x.rstrip()) venue = {} for i,k in enumerate(df['name']): if (k not in venue): venue[k] = {'January': 0 ,'February':0 , 'March': 0 , 'April':0, 'May':0,'June ':0 ,'July':0 , 'August':0,'September':0,'October':0,'November':0,'December':0} teacher = {} for i,k in enumerate(df2['name']): if (k not in teacher): teacher[k] = {'January': 0 ,'February':0 , 'March': 0 , 'April':0, 'May':0,'June ':0 ,'July':0 , 'August':0,'September':0,'October':0,'November':0,'December':0} teacher['Ajmal'] dictionary = {} liste = [] for i,ex in df2.iterrows(): nameT = ex['name'] lat1 = ex['latitude'] lon1 = ex['longitude'] sub = ex['subject'] Id = i
Re: [Tutor] enumerate over Dictionaries
Thanks Alan and Mats for the explanation. On 05/07/19 19:57, Mats Wichmann wrote: On 7/4/19 3:53 PM, Alan Gauld via Tutor wrote: Does this means that the Dict is ordered? or it is implementation dependent? Neither, it means the items in a list always have indexes starting at zero. By pure coincidence dictionaries in recent Python versions (since 3.6 or 3.7???) retain their insertion order. But that was not always the case, but the result would have been the same so far as the 0,1,2 bit goes. To be a little more precise, in 3.6 CPython insertion order was preserved as an artefact of the new implementation of dicts, but not promised to be that way. Since 3.7 it is guaranteed (it is actually in the language specification, so other Pythons have to do this too now). It's still not the same as a collections.OrderedDict, which has some useful additional features in case you care a lot about ordering. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] enumerate over Dictionaries
On 7/4/19 3:53 PM, Alan Gauld via Tutor wrote: >> Does this means that the Dict is ordered? or it is implementation dependent? > > Neither, it means the items in a list always have indexes > starting at zero. > > By pure coincidence dictionaries in recent Python versions (since 3.6 > or 3.7???) retain their insertion order. But that was not always the > case, but the result would have been the same so far as the 0,1,2 bit goes. > To be a little more precise, in 3.6 CPython insertion order was preserved as an artefact of the new implementation of dicts, but not promised to be that way. Since 3.7 it is guaranteed (it is actually in the language specification, so other Pythons have to do this too now). It's still not the same as a collections.OrderedDict, which has some useful additional features in case you care a lot about ordering. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] enumerate over Dictionaries
On 04/07/2019 18:02, Animesh Bhadra wrote: > Hi All, > My python version is 3.6.7 > I need help to understand this piece of code? > > rainbow ={"Green": "G", "Red": "R", "Blue": "B"} > # ennumerate with index, and key value > for i, (key, value) in enumerate(rainbow.items()): Lets unpick t from the inside out. What does items() return? >>> rainbow.items() dict_items([('Green', 'G'), ('Red', 'R'), ('Blue', 'B')]) For our purposes dict_items is just a fancy kind of list. In this case it is a list of tuples. Each tuple being a key,value pair. What does enumerate do to a list? It returns the index and the value of each item in the list. So if we try >>> for index, val in enumerate(rainbow.items()): print( index, val) 0 ('Green', 'G') 1 ('Red', 'R') 2 ('Blue', 'B') We get the 0,1,2 as the index of the 'list' and the corresponding tuples as the values. Now when we replace val with {key,value) Python performs tuple unpacking to populate key and value for us. > print(i, key, value) So now we get all three items printed without the tuple parens. Which is what you got. > This gives a output as always:- > > 0 Green G > 1 Red R > 2 Blue B > Does this means that the Dict is ordered? or it is implementation dependent? Neither, it means the items in a list always have indexes starting at zero. By pure coincidence dictionaries in recent Python versions (since 3.6 or 3.7???) retain their insertion order. But that was not always the case, but the result would have been the same so far as the 0,1,2 bit goes. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] enumerate over Dictionaries
Hi All, My python version is 3.6.7 I need help to understand this piece of code? rainbow ={"Green": "G", "Red": "R", "Blue": "B"} # ennumerate with index, and key value fori, (key, value) inenumerate(rainbow.items()): print(i, key, value) This gives a output as always:- 0 Green G 1 Red R 2 Blue B Does this means that the Dict is ordered? or it is implementation dependent? Thanks & Regards, Animesh. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor