-1

I would like to create another dictionary where the output will be

new_dic = {key: len(value)}

Given a dictionary containing lists in its values.

Example:

dic = {'a':[1,2,3], 'b':[4,5], 'c':[6]}

And I want to create new_dic from dic where the new_dic map keys to length of value like this:

new_dic = {'a':3, 'b':2, 'c':1}
The Thonnu
  • 3,578
  • 2
  • 8
  • 30
Simo
  • 9
  • 1
  • 2
    What have you tried, and what exactly is the problem with it? Right now what you've posted isn't syntactically valid and `dic['c']` doesn't actually _have_ a length (`len(6)` -> `TypeError`). – jonrsharpe Oct 25 '22 at 11:22
  • 1
    Take a look at the [tutorial](https://docs.python.org/3/tutorial/datastructures.html#dictionaries) which covers "dictionary comprehensions". – Mortz Oct 25 '22 at 11:24

4 Answers4

2

Not much to explain here.

new_dic = {d:len(dic[d]) if type(dic[d]) in {tuple,list,dict} else 1 for d in dic}

Swifty
  • 2,630
  • 2
  • 3
  • 21
Ankan Das
  • 268
  • 1
  • 2
  • 11
0

this will work even if you have an int not inside a list as the value in the dict

dic = {'a':[1,2,3], 'b':[4,5] , 'c':6}
new_dic = {key: len(val) if type(val) in [tuple, list] else 1 for key, val in dic.items()}
print(new_dic)
Omer Dagry
  • 537
  • 4
  • 9
0

you can use what we call a dictionary comprehension :

new_dic = {key : len(value) for key, value in dic.items()}

Note : len() functions works only on iterables (list, tuples...) and not on single values, so to use this you'll have to have your single-values also stored in a list ('c' : [6] instead of 'c' : 6)

antoine_co
  • 20
  • 5
0
getlength = lambda obj: len(obj) if hasattr(obj, '__len__') else 1

dic = {'a':[1,2,3], 'b':[4,5] , 'c':6}

new_dic = {key: getlength(value) for key, value in dic.items()}
print(new_dic.items())

The getlength checks if the object has the __len__ method and returns the length or 1, based on this answer. Then it's just a simple dict comprehension.

Output:

dict_items([('a', 3), ('b', 2), ('c', 1)])
Gábor Fekete
  • 1,343
  • 8
  • 16