Python字典与Javascript对象有什么区别?

2024-06-11 17:43:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python新手,我在读字典。从我以前使用javascript等语言的经验来看,它们对我来说就像是对象。字典可以存储列表,并与javascript中的对象共享许多相似的内容。

前python代码:

menu = {}
menu['Chicken Alfredo'] = 14.50
menu['Italian Pasta'] = 15.89
menu['Shrimp Soup'] = 12.43
menu['Persian Rice'] = 21.99

ex javascript代码:

var menu = new Object();
menu['Chicken Alfredo'] = 14.50;
menu['Italian Pasta'] = 15.89;
menu['Shrimp Soup'] = 12.43;
menu['Persian Rice'] = 21.99;

有什么区别,他们都做同样的工作,但有不同的概念?


Tags: 对象代码语言字典javascriptmenusouprice
2条回答
  • Python字典中的键必须是可散列的(例如,字符串、数字、浮点等)。

  • 以下是JavaScript中的有效对象:

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

    但是,它作为Python字典是无效的:

    python_dictionary = {name: 'Alexander Pushkin', year: 1799}
    
    # Traceback (most recent call last):
    # NameError: name 'name' is not defined
    

    一个快速的解决方案是将Python字典的键转换为字符串:

    my_dictionary = {'name': 'Alexander Pushkin', 'year': 1799}
    
  • 通过dicts,您可以在JavaScript中创建对象。它们不仅保存数据,还具有许多其他强大的功能,如构造函数。

From :

In Python, dictionaries are a form of mapping type. They can be initialized using a sequence of comma-separated name: value pairs, enclosed in curly braces. They are accessed using array notation involving square braces. The key can be any hashable, including numbers and strings.

In Javascript, a dictionary is the same as an object. It can be initialized using the same syntax as Python. The key can be a number, a string, or an identifier. Because the dictionary is also an object, the elements can be accessed either using array notation, e.g. b[i], or using property notation, e.g. b.i.

Consider an identifier used in an initializer, such as

 b = {i:j} 

In Python both i and j are evaluated, but in Javascript, only j is evaluated. In Javascript you also have the privilege of writing in the dot notation, using the identifier i. Hence in Python,

 i='k'
 j=1
 b = {i:j}
 b['k'] # -> 1 

In Javascript,

 i='k'
 j=1
 b = {i:j}
 b['i'] // -> 1
 b.i // -> 1
 // b[i], b['k'] and b.k are not defined 

In Javascript, using the identifier in dot notation is completely identical in all cases to using a string that "looks like" the identifier in array notation. Hence, b = { 'i':1 } ; b['i'] // -> 1 b.i // -> 1 When a number or boolean is used in a dictionary, Javascript will access the element using a string representation of the number or boolean. Not so in Python — a string and a number (or boolean) are different hashables.

如果您对两种语言之间的差异感兴趣,请看ans

相关问题 更多 >