字典理解 - 动态生成键值对?
Dictionary comprehension - dynamically generate key-value pairs?
我想达到与
相同的结果
{i: i+1 for i in range(4)} # {0: 1, 1: 2, 2: 3, 3: 4}
但是使用 myfunc(i)
动态生成 key: value
部分,我该怎么做?
return {i: i+1}
或 (i, i+1)
无法使用的功能:
{{i: i+1} for i in range(4)} # TypeError: unhashable type: 'dict'
dict(map(myfunc, range(4)))
参见:https://docs.python.org/3.9/library/stdtypes.html#dict
示例:
>>> 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}
在 dictionary
中对于任何 value
你需要 key
,这里是你的错误:
{{i: i+1} for i in range(4)} # TypeError: unhashable type: 'dict'
value
是 dict
,您需要为 values
.
定义 key
试试这个:
{i : {i: i+1} for i in range(4)}
# {0: {0: 1}, 1: {1: 2}, 2: {2: 3}, 3: {3: 4}}
以下理解脚本不起作用,因为您使用字典作为键。
{{i: i+1} for i in range(4)} # TypeError: unhashable type: 'dict'
是这样的:
a = {1:2}
b = {a:3} # TypeError: unhashable type: 'dict'
重点是所有字典键都应该来自不可变数据类型,例如字符串、数字、元组或冻结集。换句话说,您不能使用 可变数据类型,如字典、列表或集合作为字典键或偶数集合值。
我想达到与
相同的结果{i: i+1 for i in range(4)} # {0: 1, 1: 2, 2: 3, 3: 4}
但是使用 myfunc(i)
动态生成 key: value
部分,我该怎么做?
return {i: i+1}
或 (i, i+1)
无法使用的功能:
{{i: i+1} for i in range(4)} # TypeError: unhashable type: 'dict'
dict(map(myfunc, range(4)))
参见:https://docs.python.org/3.9/library/stdtypes.html#dict
示例:
>>> 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}
在 dictionary
中对于任何 value
你需要 key
,这里是你的错误:
{{i: i+1} for i in range(4)} # TypeError: unhashable type: 'dict'
value
是 dict
,您需要为 values
.
key
试试这个:
{i : {i: i+1} for i in range(4)}
# {0: {0: 1}, 1: {1: 2}, 2: {2: 3}, 3: {3: 4}}
以下理解脚本不起作用,因为您使用字典作为键。
{{i: i+1} for i in range(4)} # TypeError: unhashable type: 'dict'
是这样的:
a = {1:2}
b = {a:3} # TypeError: unhashable type: 'dict'
重点是所有字典键都应该来自不可变数据类型,例如字符串、数字、元组或冻结集。换句话说,您不能使用 可变数据类型,如字典、列表或集合作为字典键或偶数集合值。