简体   繁体   English

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

[英]Is there a more pythonic way to build this dictionary?

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? 什么是构建字典的“最pythonic”方式,我在序列中有值,每个键都是其值的函数? 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. 注意: values是与任何字典无关的列表。

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

至少它更短:

dict((key_from_value(value), value) for value in values)
>>> 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 }

Py3K:

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

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”的权威,但这种感觉就像是一种好方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM