What is the Python Equivalent function of Javascript Map()?

Question:

I am searching for a python equivalent code/function for the below javascript code.

let nameSetFlagMap = new Map();
Asked By: user14907490

||

Answers:

what you are looking for would be Dictionary.

nameSetFlagMap={}
#or
nameSetFlagMap=dict()

you can learn more about them here

Answered By: Kartik Narang

Ordered dictionary

from collections import OrderedDict

nameSetFlagMap = OrderedDict()
nameSetFlagMap["a"] = "a"
nameSetFlagMap["b"] = "b"
Answered By: assli100

Both answers above are wrong because they do not have the same behavior as Map() from js


from collections import OrderedDict
asd = OrderedDict()

asd2 = []

asd[asd2] = 123

asd2.append(444)

print(asd)

print(asd[asd2])

output:

Traceback (most recent call last):
  File "/home/nikel/asd.py", line 10, in <module>
    asd[asd2] = 123
TypeError: unhashable type: 'list'

from collections import OrderedDict
asd = OrderedDict()

asd2 = {}

asd[asd2] = 123

asd2.append(444)

print(asd)

print(asd[asd2])

output:

Traceback (most recent call last):
  File "/home/nikel/asd.py", line 10, in <module>
    asd[asd2] = 123
TypeError: unhashable type: 'list'

test_map = new Map()

test_map[555] = 666

list1 = []
list2 = [123]
list3 = []

test_map.set(list1, 'list1')
test_map.set(list2, 'list2')
test_map.set(list3, 'list3')

list2.push(4442)

console.log(test_map)

console.log(test_map.get(list1))
console.log(test_map.get(list2))
console.log(test_map.get(list3))

output:

Map(3) {
  [] => 'list1',
  [ 123, 4442 ] => 'list2',
  [] => 'list3',
  '555': 666
}
list1
list2
list3

I’m currently searching for analog too, so will update after I will find it.

But according to this answer looks like it is impossible.

Answered By: Николай
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.