-2

Is there a shorter way to perform an operation on each dictionary item, returning a new dictionary without having to first create an empty dictionary like i did? Note: The original a_dictionary values should not be changed.

a_dictionary = {'one': 1, 'two': 2, 'three': 3, 'four': 4}
result_dict = {}
result_dict.update((x, y*2) for x, y in a_dictionary.items())
BaRzz007
  • 3
  • 3
  • 1
    Yes, the generator expression can be passed directly to `dict`. – chepner Jul 08 '22 at 13:52
  • A dict comprehension is more readable if you are *constructing* the key/value pairs, but I would prefer `dict(some_iterable)` over `{k: v for k, v in some_iterable}`. – chepner Jul 08 '22 at 13:55
  • @chepner Trying to use `dict(some_iterable)`, This is the best i can think of `result_dict = dict(zip(a_dictionary.keys(), [x*2 for x in a_dictionary.values()]))`. – BaRzz007 Jul 13 '22 at 02:01
  • You already have the generator expression you want being passed to `result_dict.update`. Just pass it to `dict` instead: `result_dict = dict(...)`. – chepner Jul 13 '22 at 11:42

1 Answers1

2

You can use dict comprehension:

result_dict = {x: y*2 for x, y in a_dictionary.items()}
Jesper
  • 202,709
  • 46
  • 318
  • 350
bereal
  • 32,519
  • 6
  • 58
  • 104