If you come from a Java background and looking for a HashMap equivalent in Python, then you can make use of the dictionary (dict) data structure in Python.
Example in Java
import java.util.HashMap;
public class HashMapJavaExample {
public static void main(String[] args) {
// Creating a HashMap
HashMap<String, Integer> map = new HashMap<>();
// Adding entries
map.put("A", 1);
map.put("B", 2);
map.put("C", 3);
// Accessing values
int value = map.get("B");
System.out.println(value); // Output: 2
// Removing an entry
map.remove("A");
// Checking existence
boolean containsKey = map.containsKey("A");
System.out.println(containsKey); // Output: false
// Size of the map
int size = map.size();
System.out.println(size); // Output: 2
}
}
Same Example in Python
# Creating a dictionary
dictionary = {
"A": 1,
"B": 2,
"C": 3
}
# Adding entries
dictionary["D"] = 4
# Accessing values
value = dictionary["B"]
print(value) # Output: 2
# Removing an entry
del dictionary["A"]
# Checking existence
containsKey = "A" in dictionary
print(containsKey) # Output: False
# Size of the dictionary
size = len(dictionary)
print(size) # Output: 3
Let's see a comparison in a form of a table.
| Feature | Python Dictionary | Java HashMap |
|---|---|---|
| Declaration | my_dict = {} or my_dict = dict() | HashMap<KeyType, ValueType> map = new HashMap<>(); |
| Add an Entry | my_dict[key] = value | map.put(key, value); |
| Remove an Entry | del my_dict[key] | map.remove(key); |
| Accessing a Value | value = my_dict[key] | value = map.get(key); |
| Checking Existence | key in my_dict | map.containsKey(key) |
| Size | len(my_dict) | map.size() |
| Iterating Over Keys | for key in my_dict: | for (KeyType key : map.keySet()) { ... } |
| Iterating Over Values | for value in my_dict.values(): | for (ValueType value : map.values()) { ... } |
| Iterating Over Items | for key, value in my_dict.items(): | for (Map.Entry<KeyType, ValueType> entry : map.entrySet()) { ... } |
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!