What are the differences between Python Dictionaries vs Javascript Objects?

前端 未结 3 1328
花落未央
花落未央 2020-12-22 19:14

I\'m new to python and I was reading about Dictionaries. And from my previous experience with langages like javascript they seemed like objects to me. Dictionaries can store

3条回答
  •  星月不相逢
    2020-12-22 20:02

    Keys in Python dictionaries must be hashable (e.g. a string, a number, a float), while JavaScript does not have such a requirement. Consider this example:

    The following is a valid object in JavaScript:

    const javascriptObject = { name: 'Alexander Pushkin', year: 1799 }
    

    However, it would be invalid as a Python dictionary:

    python_dictionary = {name: 'Alexander Pushkin', year: 1799}
    
    
    # Results in a NameError: name 'name' is not defined
    

    A quick fix would be to convert the Python dictionary's keys into strings:

    my_dictionary = {'name': 'Alexander Pushkin', 'year': 1799}
    

提交回复
热议问题