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

We will examine how we can make a word reference in JavaScript and add key-esteem sets in it. All things considered there is no ‘word reference’ type in JavaScript except for we can make key-esteem sets by utilizing JavaScript Objects. Make another JavaScript Object which will go about as word reference.

Language structure: Key can be a string , number. Assuming that you simply compose 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:

<!DOCTYPE html>
<html>
    <head>
        <title>Dictionary in Javascript</title>
    </head>
    <body style="text-align: center;">
        <h1 style="color: green;">
            GeeksforGeeks
        </h1>
        <p>
            var dict = { <br />
            "geek" : 1 , <br />
            "for" : "2", <br />
            "geeks" : 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",
                    geeks: 3.5,
                };
 
                dict.new_geeks = "new_value";
                dict["another_new_geeks"] = 
                "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:

eevibes

Also ReadHow to Encrypt and Decrypt Strings in Python?

Leave a Reply

Your email address will not be published.