Use a Dict :

m = {"A1" : [], "B3" : []}
m["A1"].append(1)
m["A1"].append(2)
m["B3"].append(3)

Note that you need to insert the key first in the dictionary, otherwise it would show KeyError. If you want to add a new key, suppose "A2" here, simply do :

m["A2"] = []

To sort the dictionary according to its keys, use an OrderedDict :

m = OrderedDict(sorted(m.items(), key = lambda t : t[0]))

One more thing, only non-mutable items such as strings, tuples, int, etc. are allowed as keys in a python dictionary, you can't have a dictionary with a list like [1,2,3] as one of the keys.

Answer from Jarvis on Stack Overflow
🌐
TutorialsPoint
tutorialspoint.com β€Ί home β€Ί python_data_structure β€Ί python maps
Understanding Python Maps
February 21, 2009 - Python Maps also called ChainMap is a type of data structure to manage multiple dictionaries together as one unit. The combined dictionary contains the key and value pairs in a specific sequence eliminating any duplicate keys.
Top answer
1 of 2
2

Use a Dict :

m = {"A1" : [], "B3" : []}
m["A1"].append(1)
m["A1"].append(2)
m["B3"].append(3)

Note that you need to insert the key first in the dictionary, otherwise it would show KeyError. If you want to add a new key, suppose "A2" here, simply do :

m["A2"] = []

To sort the dictionary according to its keys, use an OrderedDict :

m = OrderedDict(sorted(m.items(), key = lambda t : t[0]))

One more thing, only non-mutable items such as strings, tuples, int, etc. are allowed as keys in a python dictionary, you can't have a dictionary with a list like [1,2,3] as one of the keys.

2 of 2
1

In Python, the equivalent of a hashmap is a Dict (in fact, most implementation of Dict are hashmaps). To ensure ordering across implementations, you will want to use an OrderedDict. A List is equivalent to a vector. Therefore, what you want is an OrderedDict of Lists.

from collections import OrderedDict

// Create the dictionary
d = {'A1': [1, 2], 'B2': [2, 3]}

// Order it by key
m = OrderedDict(sorted(d.items(), key=lambda t: t[0]))

// Example of appending to one of the lists
m['A1'].append(3)

print(m)

This will print:

OrderedDict([('A1', [1, 2, 3]), ('B2', [2, 3])])

You can also add additional keys containing Lists like this:

m["B2"] = [2, 3, 5, 7]

You will then need to re-sort the OrderedDict.

A minor note: Dicts in Python aren't ordered; they happen to be ordered in very new versions of CPython 3, but that's an implementation detail. Therefore, OrderedDict is the most applicable datastructure here, to ensure that your code is portable. I'm mentioning this because many people are very excited about this feature of CPython, but it's not guaranteed to work everywhere.

Discussions

history - What is the difference between JS's map and Python's dictionary? - Programming Language Design and Implementation Stack Exchange
Associative arrays are dictionaries ... abstract data type, and others. "Dictionary" types in programming languages are universally associative structures. Some consider that "dictionary" implies too much that the keys are strings, although by the same token "map" implies cartography, ... More on langdev.stackexchange.com
🌐 langdev.stackexchange.com
February 19, 2024
algorithm - Python datastructure for storage, computing and mapping - Stack Overflow
Choosing a data structure is entirely dependent on how you want to use the data. For example, if you need rapid access to named elements of your structure, then yes, a dictionary is a good choice. If you need help learning how to manipulate data structures in Python, then you should read a tutorial. More on stackoverflow.com
🌐 stackoverflow.com
Can someone please explain map() and set() ??
A Map is a datatype consisting of key-value pairs. This data type makes it easy to do lookups based on some key and get the resulting value. For example, if I had a Map consisting of keys that are ISBN numbers and values that are corresponding book titles, it would be very easy for me to check for the presence of a certain ISBN in the Map and get back whatever the corresponding title is. (This type of data structure exists in most programming languages, although it's often referred to by different names. The equivalent thing in Python is a dict.) A Set is a container datatype that guarantees uniqueness (i.e. it's impossible for two different values in the set to be identical). For example, if I had some array of strings and only wanted to see one instance of each unique string in that array, I would otherwise have to write a loop that checks a fresh array to see if the item is there, and write it to the new array only if it wasn't already present. With a Set, I can just pass the array to the Set constructor and it does that work for me. https://javascript.info/map-set More on reddit.com
🌐 r/learnjavascript
19
23
November 19, 2019
How do you implement a hash map data structure in Python without using a dict?
Do you know how hash tables are implemented, generally? More on reddit.com
🌐 r/learnpython
2
2
May 23, 2020
🌐
dbader.org
dbader.org β€Ί blog β€Ί python-dictionaries-maps-and-hashtables
Dictionaries, Maps, and Hash Tables in Python – dbader.org
April 18, 2017 - Need a dictionary, map, or hash table to implement an algorithm in your Python program? Read on to see how the Python standard library can help you. In Python, dictionaries (or β€œdicts”, for short) are a central data structure:
🌐
Medium
medium.com β€Ί pythoneers β€Ί understanding-how-maps-work-in-python-ce7102539bad
Understanding How Maps Work in Python | by Rajat Sharma | The Pythoneers | Medium
April 13, 2024 - ... In programming, a map, also known as a dictionary, hash map, or associative array, is a data structure that stores items in a collection where each item is associated with a key.
🌐
Python Like You Mean It
pythonlikeyoumeanit.com β€Ί Module2_EssentialsOfPython β€Ί DataStructures_II_Dictionaries.html
Data Structures (Part II): Dictionaries β€” Python Like You Mean It
Data Structures (Part II): Dictionaries Β· View page source Β· Python’s dictionary allows you to store key-value pairs, and then pass the dictionary a key to quickly retrieve its corresponding value. Specifically, you construct the dictionary by specifying one-way mappings from key-objects to value-objects.
🌐
The Python Coding Stack
thepythoncodingstack.com β€Ί p β€Ί mappings-in-python-data-structure-3
Finding Your Way To The Right Value β€’ Python's Mappings (Data Structure Categories #3)
May 11, 2023 - And a Python mapping enables you to find your way from one object to another. As we saw in the previous article in this series, the order of the items in a sequence matters. In a mapping, the relationship between a pair of objects is what matters. We refer to the pair of objects as the key and the value. Let's see what makes a mapping and dig a bit beneath the surface to understand this category of data structures.
🌐
Simplilearn
simplilearn.com β€Ί home β€Ί resources β€Ί software development β€Ί map function in python: simplify iterative operations
Map Function in Python: Simplify Iterative Operations
1 month ago - Learn how to use the map function in Python to simplify iterative operations. Discover its benefits, usage, and practical examples for efficient coding.
Address Β  5851 Legacy Circle, 6th Floor, Plano, TX 75024 United States
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org β€Ί dsa β€Ί introduction-to-map-data-structure
Introduction to Map – Data Structure and Algorithm Tutorials - GeeksforGeeks
July 23, 2025 - While Python's built-in dict provides the core functionality for maps, several additional types offer specialized features: collections.defaultdict: This type allows you to specify a default value for missing keys. When you try to access a key that doesn't exist, the default value is returned instead of raising a KeyError . This is useful for avoiding errors when dealing with optional data...
🌐
Real Python
realpython.com β€Ί python-mappings
Python Mappings: A Comprehensive Guide – Real Python
July 23, 2024 - In this tutorial, you'll learn the basic characteristics and operations of Python mappings. You'll explore the abstract base classes Mapping and MutableMapping and create a custom mapping.
Top answer
1 of 2
5

Background: I was an implementer of Microsoft's JScript engine in the 1990s and for a time a member of the ECMAScript technical committee.

And if so, why they aren't called the same? Given that JS is newer, why wouldn't the map be called as dictionary as well?

I see where you're coming from, and yes, every new programming language is implicitly a response to the benefits and shortcomings of previously released languages. But you are over-thinking this a bit.

The notion that in mid-1994 the designers of v1.0 of JavaScript ought to have been choosing names of their methods based on Guido's choices when he released Python 1.0 in January of that same year is charming, but unlikely. JS was not invented to compete with Python, a language for administrative scripting; it was invented to add functionality to web pages. There's no reason Python ought to have particularly been "on the radar" of the design team more than any other early-1990s language, and many reasons why it would be less germane.

Rather: JS was heavily influenced by on the one hand Java, which was perceived as too heavyweight to go in the browser, and on the other hand, Scheme, a very simple, lightweight language but with a syntax perceived as unfriendly to the web developer. Waldemar Horwat much later described the origin to me as something like "JavaScript is Common Lisp with curly braces", which I think nicely sums up the design problems that they faced.

What we should expect to see, particularly given the very short schedule on which JS was developed, is names of basic concepts and functions would be drawn from three sources:

  • The Scheme / Lisp / etc family of languages
  • The Java language
  • Whatever implementation language was used to write the library methods. (A few names in JS are taken straight from the C library.)

That's what we should expect to see. What many language designers, myself included, would prefer to see is an approach that takes into account the characteristics of the population of developers most likely to use the language.

Programming languages intended for mathematicians should use the jargon of mathematics; we'd expect "map" in the sense of "function" to be in their vocabulary. A line-of-business programmer, particularly one who came to programming through business rather than academia, is more likely to think of a map as being a plot of terrain used for navigation, so a line-of-business language ought to use a less jargon-laden term such as "lookup" or "dictionary".

"Dictionary" might be too specific though; we think of dictionaries as being functions from words to definitions, or more generally text to text, but dictionaries are often generalized key-value stores. "Keyed store" though seems to again be jargony. Design is the art of finding good compromises between many design goals. It takes judgment, and opinions will differ from designer to designer.

These considerations weighed heavily upon us when designing features for C#. You'll note for example that the monadic bind operation in C# 3.0 is not called "bind". It's called "SelectMany", because the intended developer audience was not category theorists familiar with monoids in the category of endofunctors, but rather line-of-business programmers manipulating records fetched from databases. It made much more sense to use the language of SQL queries than the language of category theorists.

2 of 2
3

Python dicts and JavaScript Maps are broadly equivalent in role, though the APIs and precise capabilities do differ. The semantics of iteration, key identity, and various additional methods differ, but you can use them for essentially the same tasks modulo that. From the user perspective, it's fair to consider them equivalent, no more different than any two implementations of the same abstract type in different languages might be.

There are programming languages that preceded Python, and both of these names have had significant currency, as do other terms like "associative array", both before and after. Any of those is a defensible choice of term to use, and in common use there is not a semantic difference between them but simply a choice by the designer, which may be for historic reasons, to avoid overloading a term too much, or simply preference. We see the same range of uses of "list", "vector", "array", and so on, which do sometimes (but not always) have subtle gradations of meaning, but these generally don't exist for the associative structures.

In Python's case, dict is in fact explicitly defined as a mapping type, and there is an abstract base class Mapping that it inherits β€” so we could arguably ask the question in the other direction too. map does also exist in the default namespace as the higher-order function, which would be a conflict, although this arrived in version 1.0 well after the dict type.


In the most formal computer-science sense a "dictionary" is actually a form of set rather than an associative structure, although I would almost consider this definition (from the Oxford Dictionary of Computer Science) obsolete at this point:

dictionary: Any data structure representing a set of elements that can support the insertion and deletion of elements as well as a test for membership.

Associative arrays are dictionaries in this sense (of key-value pairs), but so is the typical "set" abstract data type, and others. "Dictionary" types in programming languages are universally associative structures.

Some consider that "dictionary" implies too much that the keys are strings, although by the same token "map" implies cartography, so I don't think that's a strong reason to favour any particular term. It does appear that possible confusion between this sort of "map" and cartographic maps for JavaScript users was considered in 2011 when the general Map type was being introduced, but not substantively.


In the case of JavaScript in particular, there seems to be a complex but unsatisfying derivation for the use of "Map":

  • It appears that the "Map" name derives most directly from the preceding "WeakMap" type (a specialist type to allow keys to be garbage collected) that some implementations had had for years, which is an unsatisfying answer.
  • It's probable that this name in turn derived from Java's WeakHashMap type, given the general trend for JavaScript API design, but discussion logs from the earliest introduction don't seem to be available any more.
  • Java does have a Dictionary type from its very first version, but it was obsoleted by the Map type (an interface rather than a class) very shortly afterwards. All subsequent types have followed the Map pattern.

In the end, James Gosling mistakenly making Dictionary a class instead of an interface in 1995 may well be the reason for all of this, though "map" and "mapping" had been used for this already.

🌐
Codecademy
codecademy.com β€Ί article β€Ί python-data-structures
A Guide to Python Data Structures | Codecademy
Here is a tree map that visualizes the classification of data structures in Python:
🌐
Stack Overflow
stackoverflow.com β€Ί questions β€Ί 49469513 β€Ί python-datastructure-for-storage-computing-and-mapping
algorithm - Python datastructure for storage, computing and mapping - Stack Overflow
My data will likely be in this format: 1-universal Type_A=10, Type_B=20, Type_C=30 Local set 1: Type_D=40, Type_C =30, Type_B=10, Type_A=15, Type_E=45 (ie A,B,C,D,E may not be in order) Local...
🌐
GeeksforGeeks
geeksforgeeks.org β€Ί python β€Ί python-map-function
Python map() function - GeeksforGeeks
map() function in Python applies a given function to each element of an iterable (list, tuple, set, etc.) and returns a map object (iterator). It is a higher-order function used for uniform element-wise transformations, enabling concise and ...
Published Β  September 7, 2025
🌐
Reddit
reddit.com β€Ί r/learnjavascript β€Ί can someone please explain map() and set() ??
r/learnjavascript on Reddit: Can someone please explain map() and set() ??
November 19, 2019 -

I have been trying to figure out what Map and Set do through freeCodeCamp and YT tuts but nothing is sticking. I'd really appreciate the help!

Edit: Sorry for confusing people, I did not know there was a difference between Map and map or Set and set. I also am referring to Javascript, hence why this was posted in the r/learnjavascript sub.

Top answer
1 of 5
9
A Map is a datatype consisting of key-value pairs. This data type makes it easy to do lookups based on some key and get the resulting value. For example, if I had a Map consisting of keys that are ISBN numbers and values that are corresponding book titles, it would be very easy for me to check for the presence of a certain ISBN in the Map and get back whatever the corresponding title is. (This type of data structure exists in most programming languages, although it's often referred to by different names. The equivalent thing in Python is a dict.) A Set is a container datatype that guarantees uniqueness (i.e. it's impossible for two different values in the set to be identical). For example, if I had some array of strings and only wanted to see one instance of each unique string in that array, I would otherwise have to write a loop that checks a fresh array to see if the item is there, and write it to the new array only if it wasn't already present. With a Set, I can just pass the array to the Set constructor and it does that work for me. https://javascript.info/map-set
2 of 5
5
First, be careful about terminology. There is both a data structure called a Map and an array method called map . There is no relation between the two. Using lowercase and parens in the header (i.e. "map()") made it sound like you were talking about the method, though it is clear from the context you actually meant the data structure. Okay, to better understand Maps and Sets , lets start with basic vanilla JavaScript objects, which is all we had until ES6: const obj = { a: 1 }; A JavaScript object is a basically a set of key/value pairs. The values can be anything you want, but the keys are always strings (or Symbols , but don't worry about that). If you try to use something else (like a number) as a key, it will get implicitly stringified: const obj = {}; obj[1] = 'foo'; console.log(obj[1]); // foo console.log(obj['1']); // foo Maps like objects are key/value pairs, but unlike objects anything can be a key. A string, a number, an object, a function. Anything. const map = new Map([['a', 1], [1, 'foo']]); console.log(map.get(1)); // foo console.log(map.get('1')); // undefined const obj = {}; map.set(obj, 'bar'); console.log(map.get(obj)); // bar EDIT: This post originally stated that object properties do not have a reliable order. This turns out not to be true in modern browsers (thanks u/barafyrakommafem ). Although the ordering of properties is slightly different between objects and Maps, it is not really a significant differentiator between the two data structures. I have deleted the text that said otherwise. There are other differences as well, but it's really just the two one big thing you need to concern yourself with: any value, not just strings, can be a key. Now Sets are somewhat distinct. They can be thought of as just keys with no values. In the old days, we might have implemented these with objects: const VALID_INPUTS = { yes: true, no: true }; if (VALID_INPUTS[input]) { console.log(input); } else { throw new Error('Bad input!'); } This works fine, but once again, you are stringifying all of your keys. You also have to store this unneeded extra value (true in my example) with every key. Enter Sets. Like Maps, anything can be stored, not just strings, and the insertion order is maintained. And like keys in both Maps and objects, each value in a Set is unique. Unlike Maps and objects, there are no key/value pairs, just unique values. const VALID_INPUTS = new Set(['yes', 'no']); if (VALID_INPUTS.has(input)) { console.log(input); } else { throw new Error('Bad input!'); }
🌐
Programiz
programiz.com β€Ί python-programming β€Ί methods β€Ί built-in β€Ί map
Python map() Function
Become a certified Python programmer. Try Programiz PRO! ... The map() function executes a given function to each element of an iterable (such as lists, tuples, etc.).
🌐
DigitalOcean
digitalocean.com β€Ί community β€Ί tutorials β€Ί how-to-use-the-python-map-function
Ultimate Guide to Python Map Function for Data Processing | DigitalOcean
December 18, 2024 - Python map() function tutorial for more detailed examples and use cases. Understanding dictionaries in Python to enhance your knowledge of Python data structures.
🌐
Python Tips
book.pythontips.com β€Ί en β€Ί latest β€Ί map_filter.html
4. Map, Filter and Reduce β€” Python Tips 0.1 documentation
In 325+ pages, I will teach you ... approach to programming. We will discuss them one by one and understand their use cases. Map applies a function to all the items in an input_list....
🌐
Python
docs.python.org β€Ί 3 β€Ί library β€Ί collections.html
collections β€” Container datatypes
map(Counter, combinations_with_replacement('ABC', 2)) # --> AA AB AC BB BC CC ... Returns a new deque object initialized left-to-right (using append()) with data from iterable.
🌐
Python documentation
docs.python.org β€Ί 3 β€Ί reference β€Ί datamodel.html
3. Data model β€” Python 3.14.3 documentation
These represent finite sets of objects indexed by arbitrary index sets. The subscript notation a[k] selects the item indexed by k from the mapping a; this can be used in expressions and as the target of assignments or del statements.