1

I want to convert a Scala map into Row object (basically what Row(**dict) does in python I have to achieve it in Scala spark).

input : Map(com.project.name -> "A", com.project.age -> 23 )
output : Row(com.project.name="A", com.project.age = 23)

Please help.

4
  • @Dipali_Deshmukh Do you want it as dataframe or as Row? Also want are you trying to do here with this Row? Commented Nov 25, 2020 at 13:48
  • Row object , If we cannot do that then Can we convert it into dataframe and then from that dataframe we get Row object ? Row should return ultimately according to requirement, Commented Nov 25, 2020 at 13:52
  • you can check my answer below if that is helpful or near to what you were looking for Commented Nov 25, 2020 at 14:33
  • Can you check me answer? Commented Nov 30, 2020 at 8:54

2 Answers 2

3

You can use Row.fromSeq:

val m = Map("com.project.name" -> "A", "com.project.age" -> "23")
val row = Row.fromSeq(m.toSeq)

or alternatively Row(m.toSeq:_*)

both giving [(com.project.name,A),(com.project.age,23)]

Sign up to request clarification or add additional context in comments.

Comments

0

You can convert map into the dataframe as follows :

import org.apache.spark.sql.types._
import org.apache.spark.sql.functions._
val input : Map[String,String] = Map("com.project.name" -> "A", "com.project.age" -> "23")
val df = input.tail
  .foldLeft(Seq(input.head._2).toDF(input.head._1))((acc,curr) => 
acc.withColumn(curr._1,lit(curr._2)))

Now if you want to get the Row from the Dataframe you can get as follows :

val row = df.first

And if you want to see the names of the column you can get that as follows :

val columns = df.columns

2 Comments

Hi I really appreciate your response , But I want output as -> Row(com.project.name="A", com.project.age = 23).
if you want what you are looking for. you can utilize Map for that purpose as Map is itself collection of key-value pairs. Map is similar to dictionary

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.