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.
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.
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.
history - What is the difference between JS's map and Python's dictionary? - Programming Language Design and Implementation Stack Exchange
algorithm - Python datastructure for storage, computing and mapping - Stack Overflow
Can someone please explain map() and set() ??
How do you implement a hash map data structure in Python without using a dict?
Videos
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.
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.
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.