How to create dictionary and add key–value pairs dynamically?

This article will teach you how to make a dictionary in JavaScript by using objects to store key-value pairs. Although JavaScript doesn’t have a built-in “dictionary” type, we can effectively create one using JavaScript Objects. Let’s start by creating a new JavaScript Object to act as our dictionary.

Syntax:

Key can be a string , integer. If you just write key1 or any number, it will treat as a string.

var dict = { key1 : value1 , 
             key2 : value2 , 
             .... 
           };
  • Create empty dictionary
    var dict = {};
  • Adding Key-Value Pairs in Dictionary
    dict[new_key] = new_value;
    or If new_key is already present in the dictionary then the value of this will be updated to new_value.
    dict.new_key = new_value;
  • Accessing Key-Value Pairs
    var value = dict[key];
    or
    var value = dict.key;
  • Iterating the whole dictionary
    for(var key in dict) {
       console.log(key + " : " + dict[key]);
    }
    

Example:

HTML
<!DOCTYPE html>
<html>
    <head>
        <title>Dictionary in Javascript</title>
    </head>
    <body style="text-align: center;">
        <h1 style="color: green;">
            w3wiki
        </h1>
        <p>
            var dict = { <br />
            "geek" : 1 , <br />
            "for" : "2", <br />
            "Beginner" : 3.5 <br />
            }; <br />
        </p>


        <button onClick="fun()">
            Add new Key-Value Pairs
        </button>

        <p id="demo"></p>


        <!-- Script to create dictionary 
                and add key-value pairs -->
        <script>
            function fun() {
                var dict = {
                    geek: 1,
                    for: "2",
                    Beginner: 3.5,
                };

                dict.new_Beginner = "new_value";
                dict["another_new_Beginner"] = 
                "another_value";

                var to_show = "var dict = { <br>";

                for (var key in dict) {
                    to_show += '"' + key + '" : ' 
                    + dict[key] + "<br>";
                }

                to_show += " }; <br>";

                document.getElementById("demo")
                .innerHTML = to_show;
            }
        </script>
    </body>
</html>                    

Output: