-1

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

let nameSetFlagMap = new Map();
davidism
  • 121,510
  • 29
  • 395
  • 339
  • 2
    `nameSetFlagMap = {}` perhaps? Might depend on how you use that value. https://docs.python.org/3/library/stdtypes.html#typesmapping – Felix Kling Jan 06 '21 at 10:13
  • 2
    This has nothing to do with [tag:node.js] (nor, really, [tag:javascript]). Please don't tag-spam. – T.J. Crowder Jan 06 '21 at 10:15

3 Answers3

3

Ordered dictionary

from collections import OrderedDict

nameSetFlagMap = OrderedDict()
nameSetFlagMap["a"] = "a"
nameSetFlagMap["b"] = "b"
assli100
  • 555
  • 3
  • 12
1

what you are looking for would be Dictionary.

nameSetFlagMap={}
#or
nameSetFlagMap=dict()

you can learn more about them here

0

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.

  • I'm not very familiar with node.js, but that loooks to me like a trick as the `[]` is transformed into `''` as a Map key. You can use an empty string as a key in python, but not list or dict as they are mutable and unhashable. – ljmc Sep 25 '22 at 10:04
  • Oh, my mistake, I have used the Map not as it intended to be used. Updated answer. – Николай Sep 26 '22 at 14:40