Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the easiest way to take two columns of data and convert to dictionary?

I have a worksheet with data in columns A and B.

I am looking for a convenient way to take these columns and convert to dictionary where the cell in column A is the key and column B is the value, something like :

Dim dict as Dictionary
Set dict = CreateDictFromColumns("SheetName", "A", "B")

NOTE: I am already referencing the scripting dll.

like image 270
leora Avatar asked Nov 04 '15 13:11

leora


People also ask

How to convert 2 columns of dataframe to dictionary?

Another approach to convert two column values into a dictionary is to first set the column values we need as keys to be index for the dataframe and then use Pandas' to_dict() function to convert it a dictionary. This creates a dictionary for all columns in the dataframe.

How do you create a column from a Dataframe dictionary?

to_dict() method is used to convert a dataframe into a dictionary of series or list like data type depending on orient parameter. Parameters: orient: String value, ('dict', 'list', 'series', 'split', 'records', 'index') Defines which dtype to convert Columns(series into).


1 Answers

You would need to loop, E.g.

Function CreateDictFromColumns(sheet As String, keyCol As String, valCol As String) As Dictionary
    Set CreateDictFromColumns = New Dictionary
    Dim rng As Range: Set rng = Sheets(sheet).Range(keyCol & ":" & valCol)
    Dim i As Long
    Dim lastCol As Long '// for non-adjacent ("A:ZZ")
    lastCol = rng.Columns.Count
    For i = 1 To rng.Rows.Count
        If (rng(i, 1).Value = "") Then Exit Function
        CreateDictFromColumns.Add rng(i, 1).Value, rng(i, lastCol).Value
    Next
End Function

This breaks on the first empty key value cell.

like image 52
Alex K. Avatar answered Sep 29 '22 12:09

Alex K.