Reputation: 171
I have a defaultdict of sets and I need to align columns nicely during final output
Each set is displayed via ",".join(setdict[key])
to avoid ugly braces
I'm wondering is there more efficient and Pythonic way to calc longest set's string with commas
My current implementation is
def GetSetLen(setdict):
maxset = 0
for k,v in setdict.iteritems():
maxset = max(maxset, (len(",".join(setdict[k]))))
return maxset
Real example of my dict:
defaultdict(<type 'set'>, {'2235788': set(['604', '2415919103', '7']), '3674877': set(['604', '2415919103', '7'])})
Upvotes: 0
Views: 79
Reputation: 23773
map
str.join
on the values ,then map len
on the resultant strings, then find the max
>>>
>>> d
defaultdict(<type 'set'>, {'2235788': set(['604', '2415919103', '7']), '654321': ['60004', '2415919103', '765'], '000002': ['', '', ''], '000000': [''], '3674877': set(['604', '2415919103', '7']), '123456': ['604', '2415919103', '765']})
>>> map(len, map(','.join, d.itervalues()))
[16, 20, 2, 0, 16, 18]
>>> max(map(len, map(','.join, d.itervalues())))
20
>>>
You could use itertools.imap
if you didn't want to create the intermediate lists.
Upvotes: 0
Reputation: 369314
Use dict.itervalues
because the code does not take account of keys. And you don't need to make a temporary string to calculate length of the joined strings.
if not setdict:
return 0 # max(empty_setdict) raise a `ValueError`
return max(sum(map(len, v)) + len(v) - 1 if v else 0
for v in setdict.itervalues())
Upvotes: 1