实现逻辑
给定map和值n,删除map中值为value的键值对
Java
package sort_10_type.zulong; import java.util.Collection; import java.util.HashMap; import java.util.*; public class Main { //通过value移除hashmap中的键值对 public static HashMap<Integer,Integer> dropdatabyvalue(HashMap<Integer,Integer> map, int n){ Set set=map.entrySet(); Iterator iterator=set.iterator(); while (iterator.hasNext()){ Map.Entry entry=(Map.Entry) iterator.next(); if(entry.getValue()==(Integer)n) iterator.remove(); } return map; } public static void printmap(HashMap<Integer,Integer> map){ Set set=map.entrySet(); Iterator iterator=set.iterator(); while (iterator.hasNext()){ Map.Entry entry=(Map.Entry) iterator.next(); System.out.print(entry.getKey()+" "+entry.getValue()+";"); } System.out.println(); } public static void main(String[] args) { HashMap <Integer,Integer> map=new HashMap<>(); map.put(2,2); map.put(3,2); map.put(4,2); map.put(6,6); map.put(7,8); printmap(map); dropdatabyvalue(map,2); printmap(map); } }
python
# --*--coding: utf-8 --*-- def dropdata(dic,n): for k, v in dic.items(): if v==n: dic.pop(k) if __name__=='__main__': dic={1:1,2:2,3:2,4:2,5:5} dropdata(dic, 2) print dic