# Swap key-value in dictionary

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

<div class="post-metadata">

**Author:** ![powerpeanuts](https://avatars.discourse-cdn.com/v4/letter/p/e8c25b/32.png) [@powerpeanuts](https://forum.kx.com/u/powerpeanuts)\
**Post date:** [August 19, 2022, 12:00am UTC](https://forum.kx.com/t/swap-key-value-in-dictionary/13394/1 "2022-08-19T00:00:00Z")

</div>

[https://learninghub.kx.com/forums/topic/swap-key-value-in-dictionary](https://learninghub.kx.com/forums/topic/swap-key-value-in-dictionary)

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

python version: [https://stackoverflow.com/questions/51740270/python-dictionary-swap-keyvalue-pair-when-values-exist-in-mutiple-keys](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:** ![cillianreilly](https://avatars.discourse-cdn.com/v4/letter/c/7bcc69/32.png) [@cillianreilly](https://forum.kx.com/u/cillianreilly)\
**Post date:** [August 19, 2022, 12:00am UTC](https://forum.kx.com/t/swap-key-value-in-dictionary/13394/2 "2022-08-19T00:00: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!key[x]where 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!key[x]where each flip value(a:asc distinct raze x)in/:x}d 
1b
```

---

<div class="post-metadata">

**Author:** ![cillianreilly](https://avatars.discourse-cdn.com/v4/letter/c/7bcc69/32.png) [@cillianreilly](https://forum.kx.com/u/cillianreilly)\
**Post date:** [August 19, 2022, 12:00am UTC](https://forum.kx.com/t/swap-key-value-in-dictionary/13394/3 "2022-08-19T00:00:00Z")

</div>

Another method:

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

&nbsp;

&nbsp;

---

<div class="post-metadata">

**Author:** ![rolf](https://avatars.discourse-cdn.com/v4/letter/r/94ad74/32.png) [@rolf](https://forum.kx.com/u/rolf)\
**Post date:** [August 19, 2022, 12:00am UTC](https://forum.kx.com/t/swap-key-value-in-dictionary/13394/4 "2022-08-19T00:00:00Z")

</div>

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

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