# associate

> For the complete documentation index, see [llms.txt](https://kotlin.github.io/dataframe/llms.txt).

The `associate` function builds a `Map` from key–value `Pair`s produced by applying a transformation to each row of this [DataFrame](dataframe.html) using a [row expression](datarow.html#row-expressions).

API reference: [associate](https://kotlin.github.io/dataframe/api-docs/core/org.jetbrains.kotlinx.dataframe.api/associate.html)

If multiple rows produce the same key, only the last value for that key is kept. This matches the behavior of Kotlin’s standard [kotlin.collections.associate](https://kotlinlang.org/api/core/kotlin-stdlib/kotlin.sequences/associate.html) function.

The keys are in the same order as the rows. A key that occurs in several rows appears at the position of its first row, with the value of its last one.

```KOTLIN
df.associate { pairSelector }

pairSelector: (DataRow) -> Pair
```

## Related functions

* [toMap](tomap.html) — converts a [DataFrame](dataframe.html) into a `Map` by using column names as keys and their values as map values.

* [associateBy](associateby.html) — creates a map with rows as values.

## Example

```KOTLIN
df
```

[Embedded content](./resources/notebook_test_associate_1.html)

Create a map from name to age using a pair selector:

```KOTLIN
df.associate { "${name.firstName} ${name.lastName}" to age }
```

Output:

```TEXT
{
  Alice Cooper: 15,
  Bob Dylan: 45,
  Charlie Daniels: 20,
  Charlie Chaplin: 40,
  Bob Marley: 30,
  Alice Wolf: 20,
  Charlie Byrd: 30,
  Alice Smith: 30,
  Bob Brown: 15,
  Charlie Johnson: 18
}
```

Both rules are visible at once if the city is taken as the key: `London` comes first, because the first person from London is in the first row, but it holds the last one. A row without a city gives a `null` key:

```KOTLIN
df.associate { city to "${name.firstName} ${name.lastName}" }
```

Output:

```TEXT
{
  London: Bob Brown,
  Dubai: Charlie Johnson,
  Moscow: Charlie Byrd,
  Milan: Alice Smith,
  Tokyo: Bob Marley,
  null: Alice Wolf
}
```

