python - find the maximum occurrence of a string in value for all keys in a dictionary -


i have dictionary object say

d = {     '25478329': ['17647430', '376088951', '32416061', '43096205'],     '43096205': '17647430',     '376088951': ['17647430', '25478329', '32416061'],     '32416061': ['17647430', '25478329'] } 

what want find out value has occurred maximum number of times keys, e.g. in above dictionary answer '17647430'.

what did is:

def di(d):     = []     in d.values():         if isinstance(i,str):             a.append(i)         else:             j in i:                 a.append(j)     print     most_common,num_most_common = counter(a).most_common(1)[0]     print most_common,num_most_common 

can above code optimized?

chain values using itertools.chain.from_iterable():

from collections import counter itertools import chain  def di(d):     counts = counter(chain.from_iterable(         [v] if isinstance(v, str) else v v in d.itervalues()))     return counts.most_common(1)[0] 

use d.values() instead if python 3.

you'd better of if values not mix of lists , strings; i'd make lists instead.

demo:

>>> collections import counter >>> itertools import chain >>> def di(d): ...     counts = counter(chain.from_iterable( ...         [v] if isinstance(v, str) else v v in d.itervalues())) ...     return counts.most_common(1)[0] ...  >>> d = { ...     '25478329': ['17647430', '376088951', '32416061', '43096205'], ...     '43096205': '17647430', ...     '376088951': ['17647430', '25478329', '32416061'], ...     '32416061': ['17647430', '25478329'] ... } >>> di(d) ('17647430', 4) 

Comments

Popular posts from this blog

php - render data via PDO::FETCH_FUNC vs loop -

c++ - OpenCV Error: Assertion failed <scn == 3 ::scn == 4> in unknown function, -

The canvas has been tainted by cross-origin data in chrome only -