-3

I want to achieve the same result of

{i: i+1 for i in range(4)} # {0: 1, 1: 2, 2: 3, 3: 4}

But dynamically generate key: value part with myfunc(i), how do I do that?

Functions that return {i: i+1} or (i, i+1) won't work:

{{i: i+1} for i in range(4)} # TypeError: unhashable type: 'dict'
Teddy C
  • 786
  • 10
  • 13

2 Answers2

1
dict(map(myfunc, range(4)))

See: https://docs.python.org/3.9/library/stdtypes.html#dict

Example:

>>> dict([(1,2), (3,4)])
{1: 2, 3: 4}
>>> dict(map(lambda x: (x, x+1), range(4)))
{0: 1, 1: 2, 2: 3, 3: 4}
ForceBru
  • 43,482
  • 10
  • 63
  • 98
0

The following comprehension script doesn't work because you are using a dictionary as a key.

{{i: i+1} for i in range(4)} # TypeError: unhashable type: 'dict'

this is like this:

a = {1:2}
b = {a:3} # TypeError: unhashable type: 'dict'

The point is that all dictionary keys should be from immutable data types like Strings, Numbers, Tuples or Frozen Sets. In other word, you can not use mutable data types like Dictionaries, List or Sets as Dictionary key or a even Set value.

Ario
  • 549
  • 1
  • 8
  • 18
  • "you are using a dictionary as a key" that comprehension actually creates a _set_, not a dictionary, and the problem is that elements of a set must be hashable, but dictionaries aren't – ForceBru Sep 01 '21 at 16:01