3

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!

Peter
  • 2,004
  • 2
  • 24
  • 57

1 Answers1

5

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}
Akavall
  • 82,592
  • 51
  • 207
  • 251
  • Thanks a lot! But it gives me ERROR: Traceback (most recent call last): File "C:\Python\file.py", line 18, in new_dict = {k: v * 2 for k, v in dic1.iteritems()} AttributeError: 'dict' object has no attribute 'iteritems' – Peter Dec 09 '15 at 03:34
  • 2
    @Peter you are probably using `Python 3`, try `new_dict = {k: v * 2 for k, v in dic1.items()}` – Akavall Dec 09 '15 at 03:35
  • Thanks a lot! Works great! – Peter Dec 09 '15 at 03:37