Java HashMap equivalent in Python using dict data structure


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.

FeaturePython DictionaryJava HashMap
Declarationmy_dict = {} or my_dict = dict()HashMap<KeyType, ValueType> map = new HashMap<>();
Add an Entrymy_dict[key] = valuemap.put(key, value);
Remove an Entrydel my_dict[key]map.remove(key);
Accessing a Valuevalue = my_dict[key]value = map.get(key);
Checking Existencekey in my_dictmap.containsKey(key)
Sizelen(my_dict)map.size()
Iterating Over Keysfor key in my_dict:for (KeyType key : map.keySet()) { ... }
Iterating Over Valuesfor value in my_dict.values():for (ValueType value : map.values()) { ... }
Iterating Over Itemsfor key, value in my_dict.items():for (Map.Entry<KeyType, ValueType> entry : map.entrySet()) { ... }

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap