key and val are used backwards here