简体   繁体   English

字典中的字典理解

[英]Dictionary Comprehension from dictionary

I´m “testing” the Dictionaries Comprehensions using a dictionary to generate other. 我正在使用字典“测试” 字典理解来生成其他字典。

So, I want to conserve the “keys” of the first one and multiply the values *2. 所以,我想保留第一个的“键”并乘以值* 2。 And yes… I want to do it with comprehension to understand. 是的......我想通过理解来理解。

I want to reach: {4:2, 7:4, 8:6, 9:8} 我想达到: {4:2,7:4,8:6,9:8}

I am trying this: 我在尝试这个:

dic1 = {4:1, 7:2, 8:3, 9:4}

dictComp= {key:value for key in dic1.keys() for value in dic1.values() * 2}

print(dictComp)

ERROR: 错误:

Traceback (most recent call last):
  File "C:\Python\file.py", line 13, in <module>
    dictComp= {key:value for key in dic1.keys() for value in dic1.values() * 2}
  File "C:\Python\file.py", line 13, in <dictcomp>
    dictComp= {key:value for key in dic1.keys() for value in dic1.values() * 2}
TypeError: unsupported operand type(s) for *: 'dict_values' and 'int'

Anyone can help me? 有人可以帮帮我吗? Thanks a lot! 非常感谢!

Use dictionary comprehension like this: 使用这样的字典理解:

In [2]: dic1 = {4:1, 7:2, 8:3, 9:4}

In [3]: new_dict = {k: v * 2 for k, v in dic1.iteritems()} # dic1.items() for Python 3

In [4]: new_dict
Out[4]: {4: 2, 7: 4, 8: 6, 9: 8}

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

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