1

I have the following dictionary:

dict = {12:'Apples', 13:'Bananas', 14:'Oranges', 15:'Cherries'}

I want to rewrite this dictionary so that the values of dict become the keys of the new_dict. Then the values of new_dict will be the length of each new value, as follows:

new_dict = {'Apples':6, 'Bananas':7, 'Oranges':7, 'Cherries':8}

I am able to swap the values using

new_dict{}
for key,value in dict.items():
  new_dict[key] = [value]
  print(new_dict[key])
  counts = len(new_dict[key])

But the len function here counts how many values are present, not how many characters per value.

CDJB
  • 14,043
  • 5
  • 29
  • 55
DeAnna
  • 404
  • 6
  • 17
  • Does this answer your question? [How do I exchange keys with values in a dictionary?](https://stackoverflow.com/questions/1031851/how-do-i-exchange-keys-with-values-in-a-dictionary) – Sunny Patel Jan 07 '20 at 16:42

2 Answers2

5

You can do the following using a dictionary comprehension:

d = {12:'Apples', 13:'Bananas', 14:'Oranges', 15:'Cherries'}

d_new = {v: len(v) for v in d.values()}

Output:

>>> d_new
{'Apples': 6, 'Bananas': 7, 'Oranges': 7, 'Cherries': 8}

Note you should not use dict as a variable name as you overwrite the builtin dict class.

This is equivalent to the following for loop:

new_dict = {}
for v in d.values():
    new_dict[v] = len(v)
CDJB
  • 14,043
  • 5
  • 29
  • 55
2

You can use the dict function by zipping the values and the lengths:

d = {12:'Apples', 13:'Bananas', 14:'Oranges', 15:'Cherries'}
d_new = dict(zip(d.values(), map(len, d.values())))

Results

{'Apples': 6, 'Bananas': 7, 'Oranges': 7, 'Cherries': 8}
Jab
  • 26,853
  • 21
  • 75
  • 114