简体   繁体   中英

Python Dictionary: how to remove multiple keys for the same values

Which is the proper way to write this code

  getter = {
        0 : "value_1",
        1 : "value_1",
        2 : "value_1",
        3 : "value_2",
        4:  "value_3"
    }

and get the values as

   for k in keys:
    value = getter[ keys ]
    #.. then, you do other stuffs with the picked value

I want to avoid repeating "value_1"rows for different keys on dictionary declaration.

getter = {
        0 : "value_1",
        1 : "value_1",
        2 : "value_1",
        3 : "value_2",
        4:  "value_3"
    }
temp={val:key for key,val in getter.items()}
res={val:key for key, val in temp.items()}  # {2: 'value_1', 3: 'value_2', 4: 'value_3'}

You can remove duplicates from a dictionary like this.

But if you don't have to skip any key of getter , you can save and check the key after do something.

processed_value = list()
for key, value in getter.items():
    if value in processed_value:
        continue
    processed_value.append(value)
    #.. then, you do other stuffs with the picked value

如果您想要特定的键,那么您可能必须遍历字典并使用您要查找的值保存您想要的键,如果您不关心您想要的键,那么@Lazyer 答案会帮助您

Just for fun, in a single statement... Using the fact that

  • a dictionary can be constructed out of tuples and
  • removing extra values by making a new dictionary with keys the original value (need a swap -> reversed )
  • swap back
getter_new = dict(zip(*reversed(list(zip(*dict(zip(*reversed(list(zip(*getter.items()))))).items())))))

print(getter_new)
#{2: 'value_1', 3: 'value_2', 4: 'value_3'}

Notice that the last key with a repeated value will be the "dominant" one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM