Python's get method for dictionaries lets me specify what should be returned if a key doesn't exist. For my current case I want a dictionary returned. How do I do this in Javascript?
Python and javascript both have different representations for a dictionary. So you need an intermediate representation in order to pass data between them. The most commonly used intermediate representation is JSON, which is a simple lightweight data-interchange format. The dumps function converts the dict to a string.
Are there dictionaries in JavaScript? No, as of now JavaScript does not include a native “Dictionary” data type. However, Objects in JavaScript are quite flexible and can be used to create key-value pairs. These objects are quite similar to dictionaries and work alike.
Python Dictionary get() Method The get() method returns the value of the item with the specified key.
The data stored in the form of key-value pairs is called an Object or a Dictionary. Objects and dictionaries are similar; the difference lies in semantics. In JavaScript, dictionaries are called objects, whereas, in languages like Python or C#, they are called dictionaries.
There is no javascript equivalent of the python dictionary get method. If you would write it yourself, as a function, it would look like this:
function get(object, key, default_value) { var result = object[key]; return (typeof result !== "undefined") ? result : default_value; }
Use it like:
var obj = {"a": 1}; get(obj, "a", 2); // -> 1 get(obj, "b", 2); // -> 2
Note that the requested key will also be found in a prototype of obj.
If you really want a method rather than a function (obj.get("a", 2)
), you need to extend the prototype of Object. This is generally considered a bad idea though, see Extending Object.prototype JavaScript
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With