Reputation: 2394
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!
Upvotes: 5
Views: 4695
Reputation: 86128
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}
Upvotes: 7