263

I know a map is a data structure that maps keys to values. Isn't a dictionary the same? What is the difference between a map and a dictionary1?


1. I am not asking for how they are defined in language X or Y (which seems to be what generally people are asking here on SO), I want to know what is their difference in theory.

nbro
  • 15,395
  • 32
  • 113
  • 196
devoured elysium
  • 101,373
  • 131
  • 340
  • 557

12 Answers12

342

Two terms for the same thing:

  • "Map" is used by Java, C++
  • "Dictionary" is used by .Net, Python
  • "Associative array" is used by PHP

"Map" is the correct mathematical term, but it is avoided because it has a separate meaning in functional programming.

Some languages use still other terms ("Object" in Javascript, "Hash" in Ruby, "Table" in Lua), but those all have separate meanings in programming too, so I'd avoid them.

See here for more info.

BlueRaja - Danny Pflughoeft
  • 84,206
  • 33
  • 197
  • 283
  • 12
    Isn't JAVA has both Map and Dictionary? Whats the differences there? – vivek_jonam Dec 20 '12 at 14:31
  • 59
    @vivek_jonam: `Dictionary` in Java is obsolete. It's an abstract class, used before the `Map` interface was created. – BlueRaja - Danny Pflughoeft Dec 20 '12 at 16:00
  • 12
    I know the question is language agnostic, so this is the right answer, but I ended up here looking for the reason Java had both, so this comment was really the perfect thing for me. – GrandOpener Sep 01 '14 at 20:04
  • 1
    "table" is used in lua. – Deduplicator Jun 19 '15 at 16:36
  • 1
    it's also somewhat confusingly called *"Object"* in JSON (for historical reasons related to JavaScript) – Aprillion Oct 09 '15 at 13:17
  • It's called 'Object' for both JSON and JavaScript. There is no such thing as 'associative arrays' in JS. If you used named index for JS array, it get redefined as an JS 'Object' – Dan Aug 29 '16 at 02:42
  • Perl used to use "associative array" before migrating to the more succinct "hash." The leaking of implementation (vs. using an abstraction) avoids collision with the `map` function. – Michael Carman Nov 29 '18 at 14:49
  • 3
    Javascript has a "Map" data structure now too (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) – Cloxure May 21 '19 at 19:46
  • It appears that C# is in the "Dictionary" camp. Maybe that's just a consequence of `.NET`? – Robert Lewis Dec 30 '19 at 18:11
  • 1
    Javascript `Map` and `Object` are both _Map_, see [this question](https://stackoverflow.com/q/18541940/6320039) for differences between both. – Ulysse BN Feb 17 '20 at 10:12
22

One is an older term for the other. Typically the term "dictionary" was used before the mathematical term "map" took hold. Also, dictionaries tend to have a key type of string, but that's not 100% true everywhere.

nbro
  • 15,395
  • 32
  • 113
  • 196
Edwin Buck
  • 69,361
  • 7
  • 100
  • 138
22

Summary of Computer Science terminology:

  • a dictionary is a data structure representing a set of elements, with insertion, deletion, and tests for membership; the elements may be, but are not necessarily, composed of distinct key and value parts

  • a map is an associative data structure able to store a set of keys, each associated with one (or sometimes more than one - e.g. C++ multimap) value, with the ability to access and erase existing entries given only the key.


Discussion

Answering this question is complicated by programmers having seen the terms given more specific meanings in particular languages or systems they've used, but the question asks for a language agnostic comparison "in theory", which I'm taking to mean in Computing Science terms.

The terminology explained

The Oxford University Dictionary of Computer Science lists:

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

  • For example, we have a set of elements { A, B, C, D... } that we've been able to insert and could start deleting, and we're able to query "is C present?".

The Computing Science notion of map though is based on the mathematical linguistic term mapping, which the Oxford Dictionary defines as:

mapping An operation that associates each element of a given set (the domain) with one or more elements of a second set (the range).

  • As such, a map data structure provides a way to go from elements of a given set - known as "keys" in the map, to one or more elements in the second set - known as the associated "value(s)".
  • The "...or more elements in the second set" aspect can be supported by an implementation is two distinct way:
    • Many map implementations enforce uniqueness of the keys and only allow each key to be associated with one value, but that value might be able to be a data structure itself containing many values of a simpler data type, e.g. { {1,{"one", "ichi"}, {2, {"two", "ni"}} } illustrates values consisting of pairs/sets of strings.
    • Other map implementations allow duplicate keys each mapping to the same or different values - which functionally satisfies the "associates...each [key] element...with...more [than one] [value] elements" case. For example, { {1, "one"}, {1, "ichi"}, {2, "two"}, {2, "ni"} }.

Dictionary and map contrasted

So, using the strict Comp Sci terminology above, a dictionary is only a map if the interface happens to support additional operations not required of every dictionary:

  • the ability to store elements with distinct key and value components

  • the ability to retrieve and erase the value(s) given only the key

A trivial twist:

  • a map interface might not directly support a test of whether a {key,value} pair is in the container, which is pedantically a requirement of a dictionary where the elements happen to be {key,value} pairs; a map might not even have a function to test for a key, but at worst you can see if an attempted value-retrieval-by-key succeeds or fails, then if you care you can check if you retrieved an expected value.

Communicate unambiguously to your audience

⚠ Despite all the above, if you use dictionary in the strict Computing Science meaning explained above, don't expect your audience to follow you initially, or be impressed when you share and defend the terminology. The other answers to this question (and their upvotes) show how likely it is that "dictionary" will be synonymous with "map" in the experience of most programmers. Try to pick terminology that will be more widely and unambiguously understood: e.g.

  • associative container: any container storing key/value pairs with value-retrieval and erasure by key
  • hash map: a hash table implementation of an associative container
  • hash set enforcing unique keys: a hash table implementation of a dictionary storing element/values without treating them as containing distinct key/value components, wherein duplicates of the elements can not be inserted
  • balance binary tree map supporting duplicate keys: ...

Crossreferencing Comp Sci terminology with specific implementations

C++ Standard Library

  • maps: map, multimap, unordered_map, unordered_multimap
  • other dictionaries: set, multiset, unordered_set, unordered_multiset
  • note: with iterators or std::find you can erase an element and test for membership in array, vector, list, deque etc, but the container interfaces don't directly support that because finding an element is spectacularly inefficient at O(N), in some cases insert/erase is inefficient, and supporting those operations undermines the deliberately limited API the container implies - e.g. deques should only support erase/pop at the front and back and not in terms of some key. Having to do more work in code to orchestrate the search gently encourages the programmer to switch to a container data structure with more efficient searching.

...may add other languages later / feel free to edit in...

Tony Delroy
  • 102,968
  • 15
  • 177
  • 252
  • 2
    That Oxford CS definition is simply WRONG, because by that definition "dictionary" would merely be a synonym for "set", which it clearly isn't. The distinguishing characteristic of a "dictionary" is that each entry has both a key (subject to set semantics) and an associated _value_. This corresponds to a conventional natural language dictionary in which each term has a definition – DavidBooth Sep 04 '21 at 16:30
  • 2
    @DavidBooth: I'll address your last sentence first, by pointing out that there's no particular requirement that the usage when discussing "a conventional natural language dictionary" match usage in Computing Science. Which leaves the rest of your sentence as a "The Oxford CS definition is simply wrong" because you don't use or understand the term that way. Hardly convincing. To _reasonably_ argue with such a reference, you need to survey important Comp Sci. textbooks or talks and see how the term has actually been used in that academic context - a survey I hope Oxford did. – Tony Delroy Sep 04 '21 at 18:31
  • My point was not that natural language definitions are the same as CS definitions. Certainly they are not: CS definitions are more precise, though the CS terms are chosen to be _evocative_ of natural language definitions. My point was that the Oxford CS definition is clearly wrong, because by their definition a "dictionary" would be the same as a "set", which it isn't. If you disagree with this then you really _must_ read some CS books on data structures. (I still have some from my BS, MS and PhD degrees in CS, and still remember them quite well.) Hope that clarifies. – DavidBooth Sep 05 '21 at 20:52
  • 1
    @DavidBooth Well, your comments are here for readers to consider. I looked for more confirmation - first textbook I found online was from Stanford - Ullman's [Foundations of Computer Science](http://infolab.stanford.edu/~ullman/focs/ch07.pdf) where it says "The dictionary abstract data type is a kind of set, on which particular operations — insert, delete, and lookup — are performed". Examples clearly show dictionaries do not need to have key/value pairs. Until/unless you cite actual definitions from well-regarded texts, I won't be changing my answer. – Tony Delroy Sep 10 '21 at 14:53
  • Technically a dictionary is indeed "a kind of set", because it is a mapping, and a mapping is a set of pairs. But it is very misleading to merely describe a dictionary as a set, because that misses the point of it being a mapping. If a dictionary were MERELY a set, then there would be no point in calling it a dictionary. Ullman himself happens to clarify the meaning of "dictionary" on [this slide](http://infolab.stanford.edu/~ullman/fcdb/aut07/slides/uml-odl.pdf). – DavidBooth Sep 11 '21 at 02:10
  • @DavidBooth: you're just reasserting your earlier claim, which you already know I disagree with and the Oxford Dictionary disagrees with, then showing that when Ullman documents Microsoft's Object Definition Language he documents how ODL uses the term "dictionary" - so what? - it's not there as a Comp Sci definition. If you look back to Ullman's textbox, and specifically "Implementing the Dictionary Operations by a Hash Table" on pages 363/364, you'll see he illustrates very clearly a dictionary with only keys. – Tony Delroy Sep 11 '21 at 14:02
  • Further, your "if x were merely y, there'd be no point calling it z" applies equally to "if a dictionary were MERELY a map, there'd be no point calling it a dictionary.". Both set-of-key and set-of-key-value concepts have multiple names. – Tony Delroy Sep 11 '21 at 14:04
  • Try [this search](https://duckduckgo.com/?q=cs+computer+science+%22dictionary+is+a%22+site%3Aedu&ia=web). – DavidBooth Sep 11 '21 at 17:48
  • OMG, you could do your own homework and _read_ the results of that search, but since you refuse, here are quotes from SEVERAL Univ. CS courses and even one CS TEXTBOOK: **Carnegie-Mellon U**, [CS 15-112](https://www.cs.cmu.edu/~112/notes/notes-dictionaries.html): Fundamentals of Programming and CS: "A dictionary is a data structure that maps keys to values". **Cornell U**, [CS 1110](https://courses.cis.cornell.edu/courses/cs1110/2019fa/materials/definitions/#d) "A dict or dictionary is a mutable type that associates keys with values". – DavidBooth Sep 11 '21 at 21:29
  • **Intro to Computing (1st Ed)**, [David Joyner, McGraw-Hill, p176](http://lucylabs.gatech.edu/b/wp-content/uploads/2017/10/Joyner_IntroductiontoComputing_1stEdition.pdf), "A data structure comprised of key-value pairs". **Purdue U**, [course 31](http://www.cs.virginia.edu/~evans/cs1120-f11/classes/class31-notes.pdf): "Each entry in a dictionary is a pair". **U of Waterloo**, [CS 240](https://www.usna.edu/Users/cs/roche/courses/240/module04.pdf): "A dictionary is a collection of items, each of which contains a key and some data and is called a key-value pair (KVP)". – DavidBooth Sep 11 '21 at 21:36
  • **Grinnell University**, [CSC 151-01](https://osera.cs.grinnell.edu/csc151/readings/dictionaries.html): "Dictionaries allow us to represent lookup tables, associating keys with values". **Drake University** [CS65 Intro to Computer Science](https://analytics.drake.edu/~klinge/teaching/2021s/cs65/readings/dictionaries/): "a dictionary represents a mapping from keys to values". – DavidBooth Sep 11 '21 at 21:37
  • still too lazy or incompetent to separate explanations of python `dict`s (of which you've included five) from definitions intended to represent computing science (two), but that does finally show there are at least some vaguely credible authorities with definitions supporting your understanding, but certainly doesn't establish that as more authoritative than the sources I've included or make up for your earlier arrogance and unpleasantness.... – Tony Delroy Sep 18 '21 at 01:03
15

My 2 cents.

Dictionary is an abstract class in Java whereas Map is an interface. Since, Java does not support multiple inheritances, if a class extends Dictionary, it cannot extend any other class.

Therefore, the Map interface was introduced.

Dictionary class is obsolete and use of Map is preferred.

Nishit
  • 1,276
  • 2
  • 11
  • 25
  • 2
    While this answer is true, the question poster stated: `I am not asking for how they are defined in language X or Y`. This answer is Java-specific. – Bip901 Aug 27 '21 at 13:57
3

Typically I assume that a map is backed by a hash table; it connotes an unordered store. Dictionaries connote an ordered store.

There is a tree-based dictionary called a Trie.

In Lisp, it might look like this:

(a (n (d t)) n d )

Which encapsulates the words:

  • a
  • and
  • ant
  • an
  • ad

The traversal from the top to the leaf yields a word.

Paul Nathan
  • 39,638
  • 28
  • 112
  • 212
  • 4
    `Dictionary` in .Net is unordered. – BlueRaja - Danny Pflughoeft May 21 '10 at 17:35
  • 2
    Cocoa dictionaries are also unordered. – Ken May 21 '10 at 18:11
  • C++ `std::map` is ordered it's implementation is not specified in the standard, the `std::unordered_map` was introduced in c++11, it is implemented via a hash – Harald Scheirich Dec 30 '14 at 19:42
  • 3
    @HaraldScheirich - While the C++ standard doesn't specifically say "thou shalt use a red-black tree to implement `std::map`", try using anything else. An AVL tree won't work; it's insertion costs don't meet the standard. A hash won't work; a hash is unordered and hence doesn't meet the standard. The standard pretty much says "thou shalt use a red-black tree to implement `std::map`" without saying so explicitly. – David Hammen Mar 19 '15 at 14:16
  • +1. Though dictionaries are unordered in many platforms, the word connotes an order. I like the term map more. – nawfal Nov 17 '15 at 09:43
3

Not really the same thing. Maps are a subset of dictionary. Dictionary is defined here as having the insert, delete, and find functions. Map as used by Java (according to this) is a dictionary with the requirement that keys mapping to values are strictly mapped as a one-to-one function. A dictionary might have more than one key map to one value, or one key map to several values (like chaining in a hasthtable), eg Twitter hashtag searches.

As a more "real world" example, looking up a word in a dictionary can give us a number of definitions for the same word, and when we find an entry that points us to another entry (see other word), a number of words for the same list of definitions. In the real world, maps are much broader, allowing us to have locations for names or names for coordinates, but also we can find a nearest neighbor or other attributes (populations, etc), so IMHO there could be argument for a greater expansion of the map type to possibly have graph based implementations, but it would be best to always assume just the key-value pair, especially since nearest neighbor and other attributes to the value could all just be data members of the value.

java maps, despite the one-to-one requirement, can implement something more like a generalized dictionary if the value is generalized as a collection itself, or if the values are merely references to collections stored elsewhere.

Remember that Java maintainers are not the maintainers of ADT definitions, and that Java decisions are specifically for Java.

1

Other terms for this concept that are fairly common: associative array and hash.

Hank Gay
  • 70,339
  • 36
  • 160
  • 222
  • 1
    Hash is nothing to do with this. It's a method of quickly detecting whether objects are different. You are thinking of a hashmap, which uses a hash to do the Map/Dictionary job. – DJClayworth Jul 20 '11 at 14:51
  • 5
    @DJClayworth No, many programming languages actually call these things hashes. See [Ruby](http://www.ruby-doc.org/core/classes/Hash.html). I didn't design it, and I wouldn't call it that, but don't shoot the messenger. – Hank Gay Jul 21 '11 at 13:20
1

Yes, they are the same, you may add "Associative Array" to the mix.

using Hashtable or a Hash ofter refers to the implementation.

OscarRyz
  • 196,001
  • 113
  • 385
  • 569
0

These are two different terms for the same concept.
Hashtable and HashMap also refer to the same concept.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • 3
    Actually, Hashtable/Hashmap imply a specific implementation in their name (vs. say a balanced tree, which is used in the C++ std::map, for example). – Joe May 21 '10 at 17:20
  • In general, you shouldn't care about the implementation. (Except for performance reasons) Also, that's not always true; look at .Net, for example. – SLaks May 21 '10 at 17:25
0

so on a purely theoretical level.

A Dictionary is a value that can be used to locate a Linked Value. A Map is a Value that provides instructions on how to locate another values

all collections that allow non linear access (ie only get first or get last) are a Map, as even a simple Array has an index that maps to the correct value. So while a Dictionary is a Type of map, maps are a much broader range of possible function.

In Practice a its usually the mapping function that defines the name, so a HashMap is a mapped data structure that uses a hashing algorithm to link the key to the value, where as a Dictionary doesn't specify how the keys are linked to a value so could be stored via a linked list, tree or any other algorithm. from the usage end you usually don't care what the algorithm only that they work so you use a generic dictionary and only shift to one of the other structures only when you need to enfore the type of algorithm

MikeT
  • 5,398
  • 3
  • 27
  • 43
0

The main difference is that a Map, requires that all entries(value & key pair) have a unique key. If collisions occur, i.e. when a new entry has the same key as an entry already in the collection, then collision handling is required.

Usually, we handle collisions using either Separate Chaining. Or Linear Probing.

A Dictionary allows for multiple entries to be linked to the same key.

When a Map has implemented Separate Chaining, then it tends to resemble a Dictionary.

-2

I'm in a data structures class right now and my understanding is the dict() data type that can also be initialized as just dictionary = {} or with keys and values, is basically the same as how the list/array data type is used to implement stacks and queues. So, dict() is the type and maps are a resulting data structure you can choose to implement with the dictionary data type in the same way you can use the list type and choose to implement a stack or queue data structure with it.

cocoakrispies93
  • 45
  • 1
  • 11