flip keys and values in dictionary python

前端 未结 3 1686
难免孤独
难免孤独 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:15

    As you have already seen in the comments on your question, Python dictionaries cannot have duplicate keys, since there would be uncertainty as to a correct single value given a key

    This could be fixed by having parallel structure to the first, so instead of {value:key}, it would be {value:[key1, key2]}. The code to generate it would be:

    new = {}
    for key, value in z.items():
      if not value in new:
        new[value] = []
      new[value].append(key)
    

    See Adam Smith's answer for more details.

提交回复
热议问题