简体   繁体   中英

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. And yes… I want to do it with comprehension to understand.

I want to reach: {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}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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