# Swap key-value in dictionary

**URL:** https://forum.kx.com/t/swap-key-value-in-dictionary/12635
**Category:** Community Support
**Tags:** kdb-and-q
**Created:** [August 19, 2022, 3:11am UTC](https://forum.kx.com/t/swap-key-value-in-dictionary/12635 "2022-08-19T03:11:00Z")
**Posts on this page:** 4
**Page:** 1

<div class="post-metadata">

### Author: ![powerpeanuts1](https://avatars.discourse-cdn.com/v4/letter/p/b4bc9f/32.png) [@powerpeanuts1](https://forum.kx.com/u/powerpeanuts1)
#### Post date: [August 19, 2022, 3:11am UTC](https://forum.kx.com/t/swap-key-value-in-dictionary/12635/1 "2022-08-19T03:11:00Z")

</div>

hi, how can I swap key and list of values using q? Thanks!

python version:&nbsp;https://stackoverflow.com/questions/51740270/python-dictionary-swap-keyvalue-pair-when-values-exist-in-mutiple-keys

&nbsp;

for example:

1 2 3!(4 5 3;6 7 3;4 1)

becomes

1 3 4 5 6 7!(enlist 3;1 2;1 3;enlist 1;enlist 2;enlist 2)

---

<div class="post-metadata">

### Author: ![cillianreilly1](https://avatars.discourse-cdn.com/v4/letter/c/9de0a6/32.png) [@cillianreilly1](https://forum.kx.com/u/cillianreilly1)
#### Post date: [August 19, 2022, 3:34am UTC](https://forum.kx.com/t/swap-key-value-in-dictionary/12635/2 "2022-08-19T03:34:00Z")

</div>

This achieves what you’re looking for.

q)d:1 2 3!(4 5 3;6 7 3;4 1) q)r:1 3 4 5 6 7!(enlist 3;1 2;1 3;enlist 1;enlist 2;enlist 2) q){a!keywhere each flip value(a:asc distinct raze x)in/:x} d 1| ,3 3| 1 2 4| 1 3 5| ,1 6| ,2 7| ,2 q)r~{a!keywhere each flip value(a:asc distinct raze x)in/:x}d 1b

---

<div class="post-metadata">

### Author: ![cillianreilly1](https://avatars.discourse-cdn.com/v4/letter/c/9de0a6/32.png) [@cillianreilly1](https://forum.kx.com/u/cillianreilly1)
#### Post date: [August 19, 2022, 4:21am UTC](https://forum.kx.com/t/swap-key-value-in-dictionary/12635/3 "2022-08-19T04:21:00Z")

</div>

Another method:

&nbsp;

q){a!x a:asc key x:group(!). flip raze key,''value x}d 1| ,3 3| 1 2 4| 1 3 5| ,1 6| ,2 7| ,2

&nbsp;

&nbsp;

---

<div class="post-metadata">

### Author: ![Rolf1](https://avatars.discourse-cdn.com/v4/letter/r/7c8e57/32.png) [@Rolf1](https://forum.kx.com/u/Rolf1)
#### Post date: [August 19, 2022, 2:28pm UTC](https://forum.kx.com/t/swap-key-value-in-dictionary/12635/4 "2022-08-19T14:28:00Z")

</div>

{key[i]!geti:iasc key x:group(!). flip raze key,''get x}

indexing into the keys instead of doing a lookup a smidge faster
