jweinst1
11/7/2016 - 7:23 PM

sql simulation in python

sql simulation in python

#SQL - Python practice

#Implement a class called Table, that facilitates similar functions to SQL.
#This class must use a  dictionary of lists of the form 
"""
{
  "name":["tom", "bob"],
  "age":[16, 18]
}
Where the ith entry in each list of a key constitutes a member of the table.
"""

class Table:
	
	def __init__(self, *fields):
		self.matrix = {}
		self.members = 0
		#Initalizes fields from arbitrary tuple of arguments
		for elem in fields:
			self.matrix[elem] = []
		
	def __repr__(self):
		return str(self.matrix)
		
	def add_field(self, field):
		if not field in self.matrix:
			self.matrix[field] = []
		else:
			raise ValueError("Field already exists")
			
	def add_member(self, obj):
		#obj must be a dictionary with an equal number of fields to the matrix.
		for key in self.matrix:
			if key in obj:
				self.matrix[key].append(obj[key])
			else:
				raise KeyError("Key not found in table")
				
	
	#**denotes a keyword argument, where an arbitrary of arguments in the form of
	#key=value, key=value are passed into the function and bound as a dictionary
	def select(self, **args):
		result = []
		for key, val in args:
			for i in range(len(self.matrix[key])):
				if self.matrix[key][i] == val:
					result.append({k:v[i] for k in self.matrix for v in self.matrix.values() })
		return result