创建具有列表理解的字典 [英] Create a dictionary with list comprehension

查看:58
本文介绍了创建具有列表理解的字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢Python列表理解语法.

I like the Python list comprehension syntax.

它也可以用来创建字典吗?例如,通过遍历键和值对:

Can it be used to create dictionaries too? For example, by iterating over pairs of keys and values:

mydict = {(k,v) for (k,v) in blah blah blah}  # doesn't work

推荐答案

从Python 2.7和3开始,您应该只使用

From Python 2.7 and 3 onwards, you should just use the dict comprehension syntax:

{key: value for (key, value) in iterable}

在Python 2.6和更早版本中,内置的dict可以接收键/值对的迭代,因此您可以将其传递给列表推导或生成器表达式.例如:

In Python 2.6 and earlier, the dict built-in can receive an iterable of key/value pairs, so you can pass it a list comprehension or generator expression. For example:

dict((key, func(key)) for key in keys)

但是,如果您已经具有可迭代的键和/或val,则根本不需要使用理解-最简单的方法是直接调用内置的dict:

However if you already have iterable(s) of keys and/or vals, you needn't use a comprehension at all - it's simplest just call the dict built-in directly:

# consumed from any iterable yielding pairs of keys/vals
dict(pairs)

# "zipped" from two separate iterables of keys/vals
dict(zip(list_of_keys, list_of_values))

这篇关于创建具有列表理解的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆