-7

Suppose I have a Dictionary like

{
    "John"  : [1, 2, 3],
    "David" : [2, 3],
    "Stacy" : [3]
}

What do I need to do to get a resulting Dictionary that is switching the keys and values

Ex.

{
    1 : ["John"],
    2 : ["John", "David"],
    3 : ["John", "David", "Stacy"]
}

Looking to do this kind of transformation on a large dataset, ~170k keys, and values list with lengths up to 50k items. Anything else I need to worry about.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • In the future, please start with your own research. I just googled "python" plus your question title and found those questions. Check out [ask] for that and other tips. (I didn't downvote though.) – wjandrea Aug 20 '23 at 23:46
  • _What do I need to do_ You need to iterate over the existing dictionary, grab each key/value pair, and use those to construct the new dictionary. What is the actual difficulty? – John Gordon Aug 21 '23 at 00:27

1 Answers1

-1

defaultdict would be your friend here.

from collections import defaultdict
from pprint import pprint

aaa = {
    "John"  : [1, 2, 3],
    "David" : [2, 3],
    "Stacy" : [3]
}

bbb = defaultdict(list)

for k,v in aaa.items():
    for v1 in v:
        bbb[v1].append(k)

pprint(bbb)

Output:

defaultdict(<class 'list'>,
            {1: ['John'],
             2: ['John', 'David'],
             3: ['John', 'David', 'Stacy']})
Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
  • 2
    This is nearly the exact same answer as the [first suggested duplicate](https://stackoverflow.com/a/62121443/13376511). Please don't post duplicate answers to duplicate questions. At least first do a quick Google search, and CV if you find a dupe (and upvote the dupe target's answer). – Michael M. Aug 20 '23 at 23:58