[英]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.我想避免在字典声明中为不同的键重复“value_1”行。
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.但是,如果您不必跳过getter
的任何键,则可以在执行某些操作后保存并检查该键。
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只是为了好玩,在一个单一的声明中......使用这个事实
reversed
)通过使用键作为原始值的新字典来删除额外的值(需要交换 -> reversed
)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.请注意,具有重复值的最后一个键将是“主导”键。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.