是否有更多pythonic方式来构建这个字典?

时间:2022-05-26 21:45:23

What is the "most pythonic" way to build a dictionary where I have the values in a sequence and each key will be a function of its value? I'm currently using the following, but I feel like I'm just missing a cleaner way. NOTE: values is a list that is not related to any dictionary.

什么是构建字典的“最pythonic”方式,其中我有一个序列中的值,每个键将是其值的函数?我目前正在使用以下内容,但我觉得我只是错过了一种更清洁的方式。注意:值是与任何字典无关的列表。

for value in values:
    new_dict[key_from_value(value)] = value

4 个解决方案

#1


>>> l = [ 1, 2, 3, 4 ]
>>> dict( ( v, v**2 ) for v in l )
{1: 1, 2: 4, 3: 9, 4: 16}

In Python 3.0 you can use a "dict comprehension" which is basically a shorthand for the above:

在Python 3.0中,您可以使用“dict comprehension”,它基本上是上述的简写:

{ v : v**2 for v in l }

#2


At least it's shorter:

至少它更短:

dict((key_from_value(value), value) for value in values)

#3


Py3K:

{ key_for_value(value) : value for value in values }

#4


This method avoids the list comprehension syntax:

此方法避免了列表理解语法:

dict(zip(map(key_from_value, values), values))

I will never claim to be an authority on "Pythonic", but this way feels like a good way.

我永远不会声称自己是“Pythonic”的权威,但这种感觉就像是一种好方法。

#1


>>> l = [ 1, 2, 3, 4 ]
>>> dict( ( v, v**2 ) for v in l )
{1: 1, 2: 4, 3: 9, 4: 16}

In Python 3.0 you can use a "dict comprehension" which is basically a shorthand for the above:

在Python 3.0中,您可以使用“dict comprehension”,它基本上是上述的简写:

{ v : v**2 for v in l }

#2


At least it's shorter:

至少它更短:

dict((key_from_value(value), value) for value in values)

#3


Py3K:

{ key_for_value(value) : value for value in values }

#4


This method avoids the list comprehension syntax:

此方法避免了列表理解语法:

dict(zip(map(key_from_value, values), values))

I will never claim to be an authority on "Pythonic", but this way feels like a good way.

我永远不会声称自己是“Pythonic”的权威,但这种感觉就像是一种好方法。