flip keys and values in dictionary python

前端 未结 3 1717
难免孤独
难免孤独 2021-01-23 21:25

I have a dictionary called z that looks like this


{0: [0.28209479177387814, 0.19947114020071635, 0.10377687435514868, 0.07338133158686996], -1: [0.282094791773878

3条回答
  •  天命终不由人
    2021-01-23 22:11

    You can't have duplicate keys in a dictionary, but you can pair them together using tuples in a meaningful way.

    from itertools import product, chain
    
    tuples = chain.from_iterable(product(vs, [k]) for k, vs in orig_dict.items())
    # note this is identical to:
    # # tuples = []
    # # for k, vs in orig_dict.items():
    # #     for tup in [(v, k) for v in vs]:
    # #         tuples.append(tup)
    

    That will produce:

    [(0.28209479177387814, 0), (0.19947114020071635, 0),
     (0.10377687435514868, 0), (0.07338133158686996, 0),
     (0.28209479177387814, -1), (0.19947114020071635, -1),
     (0.10377687435514868, -1), (0.07338133158686996, -1)]
    

    Now if you really wanted something interesting, you could sort that and group it together.

    from itertools import groupby
    
    groups = groupby(sorted(tuples), key=lambda kv: kv[0])
    

    That creates something like:

    [(0.07338133158686996, [(0.07338133158686996, 0,
                             0.07338133158686996, -1] ),
     ... ]
    

    You could toss those into a dict by doing:

    final_dict = {k: [v[1] for v in vs] for k, vs in groups}
    

    Which should finally give:

    {0.07338133158686996: [0, -1],
     ... }
    

提交回复
热议问题