### data sample from country-capitals.csv
United Arab Emirates,Abu Dhabi,24.4666666667,54.366667,AE,Asia
Nigeria,Abuja,9.0833333333,7.533333,NG,Africa
Parse a .csv file and create a Dictionary.
import pymel.core as pm dataPath = "C:/country-capitals.csv" f = open(dataPath) line = f.readline() mapDict = {} while line: parts = line.split(",") countryObject = parts[0].strip() cityObject = parts[1].strip() latObject = parts[2].strip() lonObject = parts[3].strip() mapDict[countryObject]=[cityObject,latObject,lonObject] line = f.readline() f.close()
Dump Dictionary Data out to Pickle File
import pymel.core as pm import pickle fileName = pm.fileDialog2(fileFilter='*.p', caption='Write to a pickle file') fileObject = open(fileName[0],'wb') pickle.dump( mapDict, fileObject) fileObject.close()
Import Pickle File and Do Something with Dictionary Data
# open pickle file for reading fileName = "C:/country-capitals.p" fileObject = open(fileName,'r') # load the object from the file into var x x = pickle.load(fileObject) ## checking keys and values stored in pickle object and doing something for city,lat,lon in x.values(): print city, "has latitude of" ,lat,"and longtitude of", lon
#### only if city value is "Brasilia" for city,lat,lon in x.values(): if city == "Brasilia": print city, "has latitude of" ,lat,"and longtitude of", lon
## dictionaries are made up of key:[items] # this example checks if key i.e country in this case is "Brazil" and prints off its values i.e [capital,lat,lon] for key, values in x.items(): if key == "Brazil": print values ## also possible to drill down into individual values using index number ### ie print values[0] for capital, print values[1] for lat, print values[2] for lon.