Python Forum
5 variants to invert dictionaries with non-unique values
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
5 variants to invert dictionaries with non-unique values
#1
Hi all,

I was wondering if it was possible to rewrite the variants #1 #2 or #3 into a single line of code like variants #4 and #5?

my_map = {'a': 3, 'c': 2, 'b': 2, 'e': 3, 'd': 1, 'f': 2}

#output = {3: ['a', 'e'], 2: ['c', 'b', 'f'], 1: ['d']}

#var1
inv_map = {}
for k, v in my_map.items():
  inv_map[v] = inv_map.get(v, []) + [k]
print(inv_map)

#var2 (The best/fastest overall?)
inv_map2 = {}
for k, v in my_map.items():
  inv_map2.setdefault(v, set()).add(k)
print(inv_map2)

#var3
inv_map3 = {}
for k, v in my_map.items():
  inv_map3.setdefault(v, list()).append(k)
print(inv_map3)

#var4
print({v:[k for k in my_map.keys() if my_map[k] == v ] for k,v in my_map.items()})

#var5
print({v:[k for k in my_map if my_map[k] == v] for v in my_map.values()})
Reply
#2
Not a one-liner, but a code snippet, which is readable:

from collections import defaultdict


result = defaultdict(list)
for key, value in my_map.items():
    result[value].append(key)
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#3
(Aug-31-2020, 09:20 AM)Drakax1 Wrote: I was wondering if it was possible to rewrite the variants #1 #2 or #3 into a single
Possible,but not gone try it Wink
If have to think long about then then the readability in that line will be poor.
I would probably write this like @DeaD_EyE,as i like defaultdict and in general stuff from collections module.

Drakax1 Wrote:#var2 (The best/fastest overall?)
That's and interpretation as best also be looked at as most pythonic/readable.
Here a setup with timeit,if want to test speed.
import timeit

ver_1 = '''\
my_map = {'a': 3, 'c': 2, 'b': 2, 'e': 3, 'd': 1, 'f': 2}
inv_map = {}
for k, v in my_map.items():
  inv_map[v] = inv_map.get(v, []) + [k]'''

ver_2 = '''\
my_map = {'a': 3, 'c': 2, 'b': 2, 'e': 3, 'd': 1, 'f': 2}
inv_map2 = {}
for k, v in my_map.items():
  inv_map2.setdefault(v, set()).add(k)'''


ver_3 = '''\
from collections import defaultdict

my_map = {'a': 3, 'c': 2, 'b': 2, 'e': 3, 'd': 1, 'f': 2}
result = defaultdict(list)
for key, value in my_map.items():
    result[value].append(key)'''

ver_4_5 = '''\
my_map = {'a': 3, 'c': 2, 'b': 2, 'e': 3, 'd': 1, 'f': 2}

#{v:[k for k in my_map.keys() if my_map[k] == v ] for k,v in my_map.items()}
{v:[k for k in my_map if my_map[k] == v] for v in my_map.values()}'''

print(timeit.Timer(stmt=ver_2).timeit(number=10000000))
So ver_1 and 2 is fast.
So can get this this 10000000 run with average time down to 5-sec,but then i run PyPy Shocked
Here run ver_1.
# Python 3.8
G:\pypy3.6-v7.1.1
λ python test_map.py
19.0559965

# PyPy 3.6 ver 7.1
G:\pypy3.6-v7.1.1
λ pypy3 test_map.py
5.330786000000001
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Get an average of the unique values of a column with group by condition and assign it klllmmm 0 222 Feb-17-2024, 05:53 PM
Last Post: klllmmm
  How to invert scatter plot axis Mark17 3 2,447 Sep-22-2021, 04:45 PM
Last Post: jefsummers
  Accessing values in list of dictionaries pythonnewbie138 2 2,084 Aug-02-2020, 05:02 PM
Last Post: pythonnewbie138
  Invert Pillow image colours chesschaser 5 3,597 Jul-11-2020, 02:59 PM
Last Post: chesschaser
  Finding Max and Min Values Associated with Unique Identifiers in Python ubk046 1 2,011 May-08-2020, 12:04 PM
Last Post: anbu23
  How to compare two columns and highlight the unique values of column two using pandas shubhamjainj 0 4,235 Feb-24-2020, 06:19 AM
Last Post: shubhamjainj
  Getting Unique values from LISTS aankrose 2 2,211 Oct-17-2019, 05:33 PM
Last Post: aankrose
  How to invert pixel numbers of MNIST data set squillam 1 3,417 Oct-16-2019, 11:18 AM
Last Post: scidam
  Passing Values of Dictionaries to Function & Unable to Access Them firebird 3 2,530 Aug-03-2019, 10:25 PM
Last Post: firebird
  getting unique values and counting amounts Truman 26 9,916 Mar-15-2019, 12:44 AM
Last Post: Truman

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020