Home > Software design >  Map key to length of value in dictionary
Map key to length of value in dictionary

Time:10-26

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}

CodePudding user response:

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}

CodePudding user response:

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)

CodePudding user response:

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)

CodePudding user response:

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)])
  • Related