标签归档:dictionary-comprehension

如何在字典理解中使用if / else?

问题:如何在字典理解中使用if / else?

Python 2.7+中是否存在一种类似于以下内容的方法?

{ something_if_true if condition else something_if_false for key, value in dict_.items() }

我知道您只要使用’if’就可以做任何事情:

{ something_if_true for key, value in dict_.items() if condition}

Does there exist a way in Python 2.7+ to make something like the following?

{ something_if_true if condition else something_if_false for key, value in dict_.items() }

I know you can make anything with just ‘if’:

{ something_if_true for key, value in dict_.items() if condition}

回答 0

您已经知道了:A if test else B是有效的Python表达式。所示的dict理解的唯一问题是dict理解中表达式的位置必须有两个表达式,并用冒号分隔:

{ (some_key if condition else default_key):(something_if_true if condition
          else something_if_false) for key, value in dict_.items() }

final if子句充当过滤器,这与具有条件表达式不同。

You’ve already got it: A if test else B is a valid Python expression. The only problem with your dict comprehension as shown is that the place for an expression in a dict comprehension must have two expressions, separated by a colon:

{ (some_key if condition else default_key):(something_if_true if condition
          else something_if_false) for key, value in dict_.items() }

The final if clause acts as a filter, which is different from having the conditional expression.


回答 1

@Marcin的答案涵盖了所有内容,但是如果有人想看一个实际的示例,我在下面添加两个:

假设您有以下集合的字典

d = {'key1': {'a', 'b', 'c'}, 'key2': {'foo', 'bar'}, 'key3': {'so', 'sad'}}

并且您想创建一个新字典,其字典中的键指示值中是否包含字符串,'a'则可以使用

dout = {"a_in_values_of_{}".format(k) if 'a' in v else "a_not_in_values_of_{}".format(k): v for k, v in d.items()}

产生

{'a_in_values_of_key1': {'a', 'b', 'c'},
 'a_not_in_values_of_key2': {'bar', 'foo'},
 'a_not_in_values_of_key3': {'sad', 'so'}}

现在假设您有两个这样的字典

d1 = {'bad_key1': {'a', 'b', 'c'}, 'bad_key2': {'foo', 'bar'}, 'bad_key3': {'so', 'sad'}}
d2 = {'good_key1': {'foo', 'bar', 'xyz'}, 'good_key2': {'a', 'b', 'c'}}

如果您要替换的键中d1d2值相同,则可以

# here we assume that the values in d2 are unique
# Python 2
dout2 = {d2.keys()[d2.values().index(v1)] if v1 in d2.values() else k1: v1 for k1, v1 in d1.items()}

# Python 3
dout2 = {list(d2.keys())[list(d2.values()).index(v1)] if v1 in d2.values() else k1: v1 for k1, v1 in d1.items()}

这使

{'bad_key2': {'bar', 'foo'},
 'bad_key3': {'sad', 'so'},
 'good_key2': {'a', 'b', 'c'}}

@Marcin’s answer covers it all, but just in case someone wants to see an actual example, I add two below:

Let’s say you have the following dictionary of sets

d = {'key1': {'a', 'b', 'c'}, 'key2': {'foo', 'bar'}, 'key3': {'so', 'sad'}}

and you want to create a new dictionary whose keys indicate whether the string 'a' is contained in the values or not, you can use

dout = {"a_in_values_of_{}".format(k) if 'a' in v else "a_not_in_values_of_{}".format(k): v for k, v in d.items()}

which yields

{'a_in_values_of_key1': {'a', 'b', 'c'},
 'a_not_in_values_of_key2': {'bar', 'foo'},
 'a_not_in_values_of_key3': {'sad', 'so'}}

Now let’s suppose you have two dictionaries like this

d1 = {'bad_key1': {'a', 'b', 'c'}, 'bad_key2': {'foo', 'bar'}, 'bad_key3': {'so', 'sad'}}
d2 = {'good_key1': {'foo', 'bar', 'xyz'}, 'good_key2': {'a', 'b', 'c'}}

and you want to replace the keys in d1 by the keys of d2 if there respective values are identical, you could do

# here we assume that the values in d2 are unique
# Python 2
dout2 = {d2.keys()[d2.values().index(v1)] if v1 in d2.values() else k1: v1 for k1, v1 in d1.items()}

# Python 3
dout2 = {list(d2.keys())[list(d2.values()).index(v1)] if v1 in d2.values() else k1: v1 for k1, v1 in d1.items()}

which gives

{'bad_key2': {'bar', 'foo'},
 'bad_key3': {'sad', 'so'},
 'good_key2': {'a', 'b', 'c'}}

回答 2

如果您有不同的条件来评估键和值,@ Marcin的答案就是解决方法。

如果键和值的条件相同,则最好在生成器表达式中构建(键,值)元组并馈入dict()

dict((modify_k(k), modify_v(v)) if condition else (k, v) for k, v in dct.items())

它更易于阅读,并且每个键值仅对条件进行一次评估。

借用@Cleb的集合字典的示例:

d = {'key1': {'a', 'b', 'c'}, 'key2': {'foo', 'bar'}, 'key3': {'so', 'sad'}}

假设您只想在其后缀keys,并且在这种情况下,您希望将其替换为集合的长度。否则,键值对应保持不变。avaluevalue

dict((f"{k}_a", len(v)) if "a" in v else (k, v) for k, v in d.items())
# {'key1_a': 3, 'key2': {'bar', 'foo'}, 'key3': {'sad', 'so'}}

In case you have different conditions to evaluate for keys and values, @Marcin’s answer is the way to go.

If you have the same condition for keys and values, you’re better off with building (key, value)-tuples in a generator-expression feeding into dict():

dict((modify_k(k), modify_v(v)) if condition else (k, v) for k, v in dct.items())

It’s easier to read and the condition is only evaluated once per key, value.

Example with borrowing @Cleb’s dictionary of sets:

d = {'key1': {'a', 'b', 'c'}, 'key2': {'foo', 'bar'}, 'key3': {'so', 'sad'}}

Assume you want to suffix only keys with a in its value and you want the value replaced with the length of the set in such a case. Otherwise, the key-value pair should stay unchanged.

dict((f"{k}_a", len(v)) if "a" in v else (k, v) for k, v in d.items())
# {'key1_a': 3, 'key2': {'bar', 'foo'}, 'key3': {'sad', 'so'}}

回答 3

在字典理解中使用if / else的另一个示例

我正在为自己的办公室工作在数据输入桌面应用程序上,这种数据输入应用程序通常会从输入小部件中获取所有条目并将其转储到字典中,以进行进一步的处理,例如验证或编辑,我们必须将其返回选择的数据从文件返回到条目小部件等

第一轮使用传统编码(8行):

entries = {'name': 'Material Name', 'maxt': 'Max Working Temperature', 'ther': {100: 1.1, 200: 1.2}}

a_dic, b_dic = {}, {}

for field, value in entries.items():
    if field == 'ther':
        for k,v in value.items():
            b_dic[k] = v
        a_dic[field] = b_dic
    else:
        a_dic[field] = value
    
print(a_dic)
 {'name': 'Material Name', 'maxt': 'Max Working Temperature', 'ther': {100: 1.1, 200: 1.2}}”

第二轮我尝试使用字典理解,但是循环仍然存在(6行):

entries = {'name': 'Material Name', 'maxt': 'Max Working Temperature', 'ther': {100: 1.1, 200: 1.2}}

for field, value in entries.items():
    if field == 'ther':
        b_dic = {k:v for k,v in value.items()}
        a_dic[field] = b_dic
    else:
        a_dic[field] = value
    
print(a_dic)
 {'name': 'Material Name', 'maxt': 'Max Working Temperature', 'ther': {100: 1.1, 200: 1.2}}”

最后,使用单行字典理解语句(1行):

entries = {'name': 'Material Name', 'maxt': 'Max Working Temperature', 'ther': {100: 1.1, 200: 1.2}}

a_dic = {field:{k:v for k,v in value.items()} if field == 'ther' 
        else value for field, value in entries.items()}
    
print(a_dic)
 {'name': 'Material Name', 'maxt': 'Max Working Temperature', 'ther': {100: 1.1, 200: 1.2}}”

我使用python 3.8.3

Another example in using if/else in dictionary comprehension

I am working on data-entry desktop application for my own office work, and it is common for such data-entry application to get all entries from input widget and dump it into a dictionary for further processing like validation, or editing which we must return selected data from file back to entry widgets, etc.

The first round using traditional coding (8 lines):

entries = {'name': 'Material Name', 'maxt': 'Max Working Temperature', 'ther': {100: 1.1, 200: 1.2}}

a_dic, b_dic = {}, {}

for field, value in entries.items():
    if field == 'ther':
        for k,v in value.items():
            b_dic[k] = v
        a_dic[field] = b_dic
    else:
        a_dic[field] = value
    
print(a_dic)
“ {'name': 'Material Name', 'maxt': 'Max Working Temperature', 'ther': {100: 1.1, 200: 1.2}}”

Second round I tried to use dictionary comprehension but the loop still there (6 lines):

entries = {'name': 'Material Name', 'maxt': 'Max Working Temperature', 'ther': {100: 1.1, 200: 1.2}}

for field, value in entries.items():
    if field == 'ther':
        b_dic = {k:v for k,v in value.items()}
        a_dic[field] = b_dic
    else:
        a_dic[field] = value
    
print(a_dic)
“ {'name': 'Material Name', 'maxt': 'Max Working Temperature', 'ther': {100: 1.1, 200: 1.2}}”

Finally, with a one-line dictionary comprehension statement (1 line):

entries = {'name': 'Material Name', 'maxt': 'Max Working Temperature', 'ther': {100: 1.1, 200: 1.2}}

a_dic = {field:{k:v for k,v in value.items()} if field == 'ther' 
        else value for field, value in entries.items()}
    
print(a_dic)
“ {'name': 'Material Name', 'maxt': 'Max Working Temperature', 'ther': {100: 1.1, 200: 1.2}}”

I use python 3.8.3


为什么Python中没有元组理解?

问题:为什么Python中没有元组理解?

众所周知,列表理解

[i for i in [1, 2, 3, 4]]

并且有字典理解,例如

{i:j for i, j in {1: 'a', 2: 'b'}.items()}

(i for i in (1, 2, 3))

最终将成为生成器,而不是tuple理解力。这是为什么?

我的猜测是a tuple是不可变的,但这似乎并不是答案。

As we all know, there’s list comprehension, like

[i for i in [1, 2, 3, 4]]

and there is dictionary comprehension, like

{i:j for i, j in {1: 'a', 2: 'b'}.items()}

but

(i for i in (1, 2, 3))

will end up in a generator, not a tuple comprehension. Why is that?

My guess is that a tuple is immutable, but this does not seem to be the answer.


回答 0

您可以使用生成器表达式:

tuple(i for i in (1, 2, 3))

但是对于…生成器表达式,已经使用了括号。

You can use a generator expression:

tuple(i for i in (1, 2, 3))

but parentheses were already taken for … generator expressions.


回答 1

Raymond Hettinger(Python核心开发人员之一)在最近的一条推文中曾这样说过元组:

#python提示:通常,列表用于循环;结构的元组。列表是同质的;元组异构。列出可变长度。

(对我来说)支持这样的想法:如果序列中的项目相关性足以由生成器生成,那么它应该是一个列表。尽管元组是可迭代的,并且看起来只是一个不可变的列表,但它实际上与C结构的Python等效:

struct {
    int a;
    char b;
    float c;
} foo;

struct foo x = { 3, 'g', 5.9 };

成为Python

x = (3, 'g', 5.9)

Raymond Hettinger (one of the Python core developers) had this to say about tuples in a recent tweet:

#python tip: Generally, lists are for looping; tuples for structs. Lists are homogeneous; tuples heterogeneous. Lists for variable length.

This (to me) supports the idea that if the items in a sequence are related enough to be generated by a, well, generator, then it should be a list. Although a tuple is iterable and seems like simply a immutable list, it’s really the Python equivalent of a C struct:

struct {
    int a;
    char b;
    float c;
} foo;

struct foo x = { 3, 'g', 5.9 };

becomes in Python

x = (3, 'g', 5.9)

回答 2

从Python 3.5开始,您还可以使用splat *解包语法来解压缩生成器表达式:

*(x for x in range(10)),

Since Python 3.5, you can also use splat * unpacking syntax to unpack a generator expresion:

*(x for x in range(10)),

回答 3

正如另一位发帖人macm所述,从生成器创建元组的最快方法是tuple([generator])


性能比较

  • 清单理解:

    $ python3 -m timeit "a = [i for i in range(1000)]"
    10000 loops, best of 3: 27.4 usec per loop
    
  • 来自列表理解的元组:

    $ python3 -m timeit "a = tuple([i for i in range(1000)])"
    10000 loops, best of 3: 30.2 usec per loop
    
  • 生成器中的元组:

    $ python3 -m timeit "a = tuple(i for i in range(1000))"
    10000 loops, best of 3: 50.4 usec per loop
    
  • 打开包装的元组:

    $ python3 -m timeit "a = *(i for i in range(1000)),"
    10000 loops, best of 3: 52.7 usec per loop
    

我的python版本

$ python3 --version
Python 3.6.3

因此,除非性能不是问题,否则应始终从列表理解中创建一个元组。

As another poster macm mentioned, the fastest way to create a tuple from a generator is tuple([generator]).


Performance Comparison

  • List comprehension:

    $ python3 -m timeit "a = [i for i in range(1000)]"
    10000 loops, best of 3: 27.4 usec per loop
    
  • Tuple from list comprehension:

    $ python3 -m timeit "a = tuple([i for i in range(1000)])"
    10000 loops, best of 3: 30.2 usec per loop
    
  • Tuple from generator:

    $ python3 -m timeit "a = tuple(i for i in range(1000))"
    10000 loops, best of 3: 50.4 usec per loop
    
  • Tuple from unpacking:

    $ python3 -m timeit "a = *(i for i in range(1000)),"
    10000 loops, best of 3: 52.7 usec per loop
    

My version of python:

$ python3 --version
Python 3.6.3

So you should always create a tuple from a list comprehension unless performance is not an issue.


回答 4

理解通过循环或迭代项并将它们分配到容器中来工作,元组无法接收分配。

创建元组后,将无法对其进行追加,扩展或分配。修改元组的唯一方法是是否可以将其对象之一本身分配给它(是非元组容器)。因为元组仅持有对此类对象的引用。

另外-元组有自己的构造函数tuple(),您可以提供任何迭代器。这意味着要创建一个元组,您可以执行以下操作:

tuple(i for i in (1,2,3))

Comprehension works by looping or iterating over items and assigning them into a container, a Tuple is unable to receive assignments.

Once a Tuple is created, it can not be appended to, extended, or assigned to. The only way to modify a Tuple is if one of its objects can itself be assigned to (is a non-tuple container). Because the Tuple is only holding a reference to that kind of object.

Also – a tuple has its own constructor tuple() which you can give any iterator. Which means that to create a tuple, you could do:

tuple(i for i in (1,2,3))

回答 5

我最好的猜测是,他们用完了括号,并认为这对警告添加“丑陋”语法没有足够的帮助…

My best guess is that they ran out of brackets and didn’t think it would be useful enough to warrent adding an “ugly” syntax …


回答 6

元组不能像列表一样有效地附加。

因此,元组理解将需要在内部使用列表,然后转换为元组。

那将与您现在所做的相同:tuple([comprehension])

Tuples cannot efficiently be appended like a list.

So a tuple comprehension would need to use a list internally and then convert to a tuple.

That would be the same as what you do now : tuple( [ comprehension ] )


回答 7

括号不会创建元组。又名一个=(两个)不是元组。唯一的解决方法是一个=(两个)或一个=元组(两个)。因此,解决方案是:

tuple(i for i in myothertupleorlistordict) 

Parentheses do not create a tuple. aka one = (two) is not a tuple. The only way around is either one = (two,) or one = tuple(two). So a solution is:

tuple(i for i in myothertupleorlistordict) 

回答 8

我相信这只是为了清楚起见,我们不想用太多不同的符号来使语言混乱。同样tuple也不需要理解,可以使用列表,而速度差异可以忽略不计,而不是像dict理解而不是list理解。

I believe it’s simply for the sake of clarity, we do not want to clutter the language with too many different symbols. Also a tuple comprehension is never necessary, a list can just be used instead with negligible speed differences, unlike a dict comprehension as opposed to a list comprehension.


回答 9

我们可以从列表理解中生成元组。下一个将两个数字顺序加到一个元组中,并给出一个从0-9的列表。

>>> print k
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
>>> r= [tuple(k[i:i+2]) for i in xrange(10) if not i%2]
>>> print r
[(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)]

We can generate tuples from a list comprehension. The following one adds two numbers sequentially into a tuple and gives a list from numbers 0-9.

>>> print k
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
>>> r= [tuple(k[i:i+2]) for i in xrange(10) if not i%2]
>>> print r
[(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)]

创建具有列表理解的字典

问题:创建具有列表理解的字典

我喜欢Python列表理解语法。

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

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

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

回答 0

从Python 2.7和3开始,您应该只使用dict comprehension语法

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

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

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

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

# 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))

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

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

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)

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))

回答 1

在Python 3和Python 2.7+中,字典理解如下所示:

d = {k:v for k, v in iterable}

对于Python 2.6或更早版本,请参见fortran的答案

In Python 3 and Python 2.7+, dictionary comprehensions look like the below:

d = {k:v for k, v in iterable}

For Python 2.6 or earlier, see fortran’s answer.


回答 2

实际上,如果它已经包含某种映射,则您甚至不需要遍历可迭代对象,dict构造函数会为您轻松地做到这一点:

>>> ts = [(1, 2), (3, 4), (5, 6)]
>>> dict(ts)
{1: 2, 3: 4, 5: 6}
>>> gen = ((i, i+1) for i in range(1, 6, 2))
>>> gen
<generator object <genexpr> at 0xb7201c5c>
>>> dict(gen)
{1: 2, 3: 4, 5: 6}

In fact, you don’t even need to iterate over the iterable if it already comprehends some kind of mapping, the dict constructor doing it graciously for you:

>>> ts = [(1, 2), (3, 4), (5, 6)]
>>> dict(ts)
{1: 2, 3: 4, 5: 6}
>>> gen = ((i, i+1) for i in range(1, 6, 2))
>>> gen
<generator object <genexpr> at 0xb7201c5c>
>>> dict(gen)
{1: 2, 3: 4, 5: 6}

回答 3

在Python 2.7中,它类似于:

>>> list1, list2 = ['a', 'b', 'c'], [1,2,3]
>>> dict( zip( list1, list2))
{'a': 1, 'c': 3, 'b': 2}

压缩他们

In Python 2.7, it goes like:

>>> list1, list2 = ['a', 'b', 'c'], [1,2,3]
>>> dict( zip( list1, list2))
{'a': 1, 'c': 3, 'b': 2}

Zip them!


回答 4

在Python中创建具有列表理解的字典

我喜欢Python列表理解语法。

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

mydict = {(k,v) for (k,v) in blah blah blah}

您正在寻找“ dict comprehension”一词-实际上是:

mydict = {k: v for k, v in iterable}

假设blah blah blah是两个元组的迭代-您是如此亲密。让我们创建一些类似的“ blah”:

blahs = [('blah0', 'blah'), ('blah1', 'blah'), ('blah2', 'blah'), ('blah3', 'blah')]

Dict理解语法:

现在,这里的语法是映射部分。使它成为dict理解而不是set理解(这是您的伪代码近似值)的是冒号,:如下所示:

mydict = {k: v for k, v in blahs}

而且我们看到它起作用了,并且应该保留Python 3.7的插入顺序:

>>> mydict
{'blah0': 'blah', 'blah1': 'blah', 'blah2': 'blah', 'blah3': 'blah'}

在Python 2和3.6以下版本中,不能保证顺序:

>>> mydict
{'blah0': 'blah', 'blah1': 'blah', 'blah3': 'blah', 'blah2': 'blah'}

添加过滤器:

所有的理解都具有一个映射组件和一个过滤组件,您可以为它们提供任意表达式。

因此,您可以在末尾添加一个过滤器部分:

>>> mydict = {k: v for k, v in blahs if not int(k[-1]) % 2}
>>> mydict
{'blah0': 'blah', 'blah2': 'blah'}

在这里,我们只是测试最后符是否可被2整除以在映射键和值之前过滤掉数据。

Create a dictionary with list comprehension in 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}

You’re looking for the phrase “dict comprehension” – it’s actually:

mydict = {k: v for k, v in iterable}

Assuming blah blah blah is an iterable of two-tuples – you’re so close. Let’s create some “blahs” like that:

blahs = [('blah0', 'blah'), ('blah1', 'blah'), ('blah2', 'blah'), ('blah3', 'blah')]

Dict comprehension syntax:

Now the syntax here is the mapping part. What makes this a dict comprehension instead of a set comprehension (which is what your pseudo-code approximates) is the colon, : like below:

mydict = {k: v for k, v in blahs}

And we see that it worked, and should retain insertion order as-of Python 3.7:

>>> mydict
{'blah0': 'blah', 'blah1': 'blah', 'blah2': 'blah', 'blah3': 'blah'}

In Python 2 and up to 3.6, order was not guaranteed:

>>> mydict
{'blah0': 'blah', 'blah1': 'blah', 'blah3': 'blah', 'blah2': 'blah'}

Adding a Filter:

All comprehensions feature a mapping component and a filtering component that you can provide with arbitrary expressions.

So you can add a filter part to the end:

>>> mydict = {k: v for k, v in blahs if not int(k[-1]) % 2}
>>> mydict
{'blah0': 'blah', 'blah2': 'blah'}

Here we are just testing for if the last character is divisible by 2 to filter out data before mapping the keys and values.


回答 5

Python版本<2.7 (RIP,2010年7月3日至2019年12月31日),请执行以下操作:

d = dict((i,True) for i in [1,2,3])

Python版本> = 2.7,请执行以下操作:

d = {i: True for i in [1,2,3]}

Python version < 2.7(RIP, 3 July 2010 – 31 December 2019), do the below:

d = dict((i,True) for i in [1,2,3])

Python version >= 2.7, do the below:

d = {i: True for i in [1,2,3]}

回答 6

如果要遍历键key_list列表和值列表,请添加到@fortran的答案中value_list

d = dict((key, value) for (key, value) in zip(key_list, value_list))

要么

d = {(key, value) for (key, value) in zip(key_list, value_list)}

To add onto @fortran’s answer, if you want to iterate over a list of keys key_list as well as a list of values value_list:

d = dict((key, value) for (key, value) in zip(key_list, value_list))

or

d = {(key, value) for (key, value) in zip(key_list, value_list)}

回答 7

这是使用dict理解创建字典的另一个示例:

我在这里要做的是在每对字典中创建一个字母字典。是英文字母及其在英文字母中的对应位置

>>> import string
>>> dict1 = {value: (int(key) + 1) for key, value in 
enumerate(list(string.ascii_lowercase))}
>>> dict1
{'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4, 'g': 7, 'f': 6, 'i': 9, 'h': 8, 
'k': 11, 'j': 10, 'm': 13, 'l': 12, 'o': 15, 'n': 14, 'q': 17, 'p': 16, 's': 
19, 'r': 18, 'u': 21, 't': 20, 'w': 23, 'v': 22, 'y': 25, 'x': 24, 'z': 26}
>>> 

请注意,此处使用枚举可获取列表中的字母及其索引,并交换字母和索引以生成字典的键值对

希望它对您的字典组合有个好主意,并鼓励您更多地使用它来使代码紧凑

Here is another example of dictionary creation using dict comprehension:

What i am tring to do here is to create a alphabet dictionary where each pair; is the english letter and its corresponding position in english alphabet

>>> import string
>>> dict1 = {value: (int(key) + 1) for key, value in 
enumerate(list(string.ascii_lowercase))}
>>> dict1
{'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4, 'g': 7, 'f': 6, 'i': 9, 'h': 8, 
'k': 11, 'j': 10, 'm': 13, 'l': 12, 'o': 15, 'n': 14, 'q': 17, 'p': 16, 's': 
19, 'r': 18, 'u': 21, 't': 20, 'w': 23, 'v': 22, 'y': 25, 'x': 24, 'z': 26}
>>> 

Notice the use of enumerate here to get a list of alphabets and their indexes in the list and swapping the alphabets and indices to generate the key value pair for dictionary

Hope it gives a good idea of dictionary comp to you and encourages you to use it more often to make your code compact


回答 8

尝试这个,

def get_dic_from_two_lists(keys, values):
    return { keys[i] : values[i] for i in range(len(keys)) }

假设我们有两个清单,国家首都

country = ['India', 'Pakistan', 'China']
capital = ['New Delhi', 'Islamabad', 'Beijing']

然后从两个列表中创建字典:

print get_dic_from_two_lists(country, capital)

输出是这样的,

{'Pakistan': 'Islamabad', 'China': 'Beijing', 'India': 'New Delhi'}

Try this,

def get_dic_from_two_lists(keys, values):
    return { keys[i] : values[i] for i in range(len(keys)) }

Assume we have two lists country and capital

country = ['India', 'Pakistan', 'China']
capital = ['New Delhi', 'Islamabad', 'Beijing']

Then create dictionary from the two lists:

print get_dic_from_two_lists(country, capital)

The output is like this,

{'Pakistan': 'Islamabad', 'China': 'Beijing', 'India': 'New Delhi'}

回答 9

>>> {k: v**3 for (k, v) in zip(string.ascii_lowercase, range(26))}

Python支持dict理解,它允许您使用类似的简洁语法在运行时表示字典的创建。

字典理解采用{key:(key,value)inerable中的值}的形式。该语法是在Python 3中引入的,并且一直移植到Python 2.7,因此,无论安装了哪个版本的Python,您都应该能够使用它。

一个典型的例子是获取两个列表并创建一个字典,其中第一个列表中每个位置的项成为键,而第二个列表中相应位置的项变为值。

此推导中使用的zip函数返回一个元组的迭代器,其中元组中的每个元素均取自每个输入可迭代对象中的相同位置。在上面的示例中,返回的迭代器包含元组(“ a”,1),(“ b”,2)等。

输出:

{‘i’:512,’e’:64,’o’:2744,’h’:343,’l’:1331,’s’:5832,’b’:1,’w’:10648,’ c’:8,’x’:12167,’y’:13824,’t’:6859,’p’:3375,’d’:27,’j’:729,’a’:0,’z’ :15625,’f’:125,’q’:4096,’u’:8000,’n’:2197,’m’:1728,’r’:4913,’k’:1000,’g’:216 ,’v’:9261}

>>> {k: v**3 for (k, v) in zip(string.ascii_lowercase, range(26))}

Python supports dict comprehensions, which allow you to express the creation of dictionaries at runtime using a similarly concise syntax.

A dictionary comprehension takes the form {key: value for (key, value) in iterable}. This syntax was introduced in Python 3 and backported as far as Python 2.7, so you should be able to use it regardless of which version of Python you have installed.

A canonical example is taking two lists and creating a dictionary where the item at each position in the first list becomes a key and the item at the corresponding position in the second list becomes the value.

The zip function used inside this comprehension returns an iterator of tuples, where each element in the tuple is taken from the same position in each of the input iterables. In the example above, the returned iterator contains the tuples (“a”, 1), (“b”, 2), etc.

Output:

{‘i’: 512, ‘e’: 64, ‘o’: 2744, ‘h’: 343, ‘l’: 1331, ‘s’: 5832, ‘b’: 1, ‘w’: 10648, ‘c’: 8, ‘x’: 12167, ‘y’: 13824, ‘t’: 6859, ‘p’: 3375, ‘d’: 27, ‘j’: 729, ‘a’: 0, ‘z’: 15625, ‘f’: 125, ‘q’: 4096, ‘u’: 8000, ‘n’: 2197, ‘m’: 1728, ‘r’: 4913, ‘k’: 1000, ‘g’: 216, ‘v’: 9261}


回答 10

此代码将使用列表推导为多个具有不同值的列表创建字典,这些字典可用于 pd.DataFrame()

#Multiple lists 
model=['A', 'B', 'C', 'D']
launched=[1983,1984,1984,1984]
discontinued=[1986, 1985, 1984, 1986]

#Dictionary with list comprehension
keys=['model','launched','discontinued']
vals=[model, launched,discontinued]
data = {key:vals[n] for n, key in enumerate(keys)}

enumerate将通过nvals使其与key列表匹配

This code will create dictionary using list comprehension for multiple lists with different values that can be used for pd.DataFrame()

#Multiple lists 
model=['A', 'B', 'C', 'D']
launched=[1983,1984,1984,1984]
discontinued=[1986, 1985, 1984, 1986]

#Dictionary with list comprehension
keys=['model','launched','discontinued']
vals=[model, launched,discontinued]
data = {key:vals[n] for n, key in enumerate(keys)}

enumerate will pass n to vals to match each key with its list


回答 11

仅举另一个例子。假设您有以下列表:

nums = [4,2,2,1,3]

并且您想将其变成字典,其中键是索引,值是列表中的元素。您可以使用以下代码行执行此操作:

{index:nums[index] for index in range(0,len(nums))}

Just to throw in another example. Imagine you have the following list:

nums = [4,2,2,1,3]

and you want to turn it into a dict where the key is the index and value is the element in the list. You can do so with the following line of code:

{index:nums[index] for index in range(0,len(nums))}

回答 12

您可以为每对创建一个新的字典并将其与上一个字典合并:

reduce(lambda p, q: {**p, **{q[0]: q[1]}}, bla bla bla, {})

显然,这种方法需要reduce来自functools

You can create a new dict for each pair and merge it with the previous dict:

reduce(lambda p, q: {**p, **{q[0]: q[1]}}, bla bla bla, {})

Obviously this approaches requires reduce from functools.