75

I'm new to Python and I was reading about Dictionaries. And from my previous experience with languages like Javascript, they seemed like objects to me. Dictionaries can store lists and share many similaraties to objects in Javascript.

ex python code:

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

ex javascript code:

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

What's the difference here, they both do the same job, but there different concepts?

6
  • 13
    the python code is also js... Commented Jan 8, 2014 at 5:12
  • 19
    Javascript allows things like menu.chicken as an alias for menu['chicken'] (IIRC), but python doesn't allow that. Also, a python dictionary will raise an KeyError if a requested item isn't present. Javascript will return undefined (again, IIRC)... Commented Jan 8, 2014 at 5:14
  • 6
    @dandavis syntactically they are the same, but a dictionary might behave differently than a JS object Commented Jan 8, 2014 at 5:14
  • 6
    In python dict you can use any immutable type as key(string, int, tuple, frozenset, etc), but in js objects all keys are converted to strings. So, menu['1'] and menu[1] are same thing in js, but not in Python dicts. Commented Jan 8, 2014 at 5:24
  • 2
    BTW there is a python package that provides attribute-style access for dictionaries. It allows things like menu.chicken, menu.chicken = 1, etc. github.com/Infinidat/munch Commented Jun 13, 2017 at 14:29

4 Answers 4

79

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.

If you are interested in differences between both languages, then look at ans

Sign up to request clarification or add additional context in comments.

3 Comments

The -> operator doesn't exist in Python (second block of code)
@Jacquot he's just saying that b['k'] would be a value of 1
@tisaconundrum yeah I know, the -> 1 has been commented out since I commented ; I guess at the time I was just picky, for those who are prompt to copy-paste code to see what it outputs
21
  1. Keys in Python dictionaries must be hashable (e.g. a string, a number, a float), while JavaScript does not have such a requirement.

  2. 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}

3 Comments

In Javascript, what type are name and year? Are they typecasted to strings?
@Zaku string and Number
I've always been annoyed by JS letting that happen.
0

I think in js object you can refer to the object items by this keyword, and it is more like a class . you can write an object referring to its own properties and dictionaries in python are just maps.

object = { name: "somename",
           _rpr_: function(){
           return this.name
           }
           }

Comments

0

With given difference write in submitted answers one difference is missing. That is, JavaScript objects are not iterable, but Python dictionaries are. If we looped over a python dictionary and a JavaScript object we would get a TypeError in case of JavaScript (code snippet is given below). for e.g. in the case of a Python dictionary:

dict={'Name':'Ram',
      'Occupation': 'Scientist',
      'salary': '50000'
         }

If we iterate over dict with for loop, we get the following output.

for i  in  dict:
    print(i)


>>> Ram
    Occupation
    Salary

But in case of JavaScript:

dict={Name:'Ram',
      Occupation: 'Scientist',
      salary: '50000'​}

for(i of dict){
  console.log(i)}
>>TypeError dict in not iterable.

2 Comments

At least as of 2022 and testing in Chrome, this is not accurate. If you change it to i in dict (you have a typo), it iterates just fine
Is that a typo of?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.