top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Find the max number of elements in lists as value in a dictionary using Python?

+1 vote
233 views

I want to find the maximal number of elements contained in a nested dictionary, e.g.

data = {
 'violations':
 {
 'col1': {'err': [elem1, elem2, elem3]},
 'col2': {'err': [elem1, elem2]}
 }
 }

so to find the maximal number of elements in the lists for key 'err' in key 'col1' and 'col2'. Also key 'violations' may contain many keys (e.g. 'col1' , 'col2', 'col3' etc), so what's the best way to do this (using a loop)?

max = 0for col in data.violations:
 if max < len(data.violations.col.err):
 max = len(data.violations.col.err)
posted May 25, 2016 by anonymous

Looking for an answer?  Promote on:
Facebook Share Button Twitter Share Button LinkedIn Share Button

Similar Questions
+1 vote

A list can contain different types of elements but I am not able to understand how max () method work with different types of data elements.

+2 votes

How can I flatten just a specific sublist of each list in a list of lists?

So if I had this data

[ ['46295', 'Montauk', '3', '60', '85', ['19', '5', '1', '0 $277790.00']],
 ['46295', 'Dark Eyes', '5', '59', '83', ['6', '4', '1', '0 $105625.00']],
 ['46295', 'Machinegun Jubs', '6', '53', '77', ['6', '2', '1', '1 $71685.00']],
 ['46295', 'Zara Bay', '1', '53', '77', ['12', '2', '3', '3 $112645.00']]]

How can I make it be

[ ['46295', 'Montauk', '3', '60', '85', '19', '5', '1', '0 $277790.00'],
 ['46295', 'Dark Eyes', '5', '59', '83', '6', '4', '1', '0 $105625.00'],
 ['46295', 'Machinegun Jubs', '6', '53', '77', '6', '2', '1', '1 $71685.00'],
 ['46295', 'Zara Bay', '1', '53', '77', '12', '2', '3', '3 $112645.00']]

Been looking around but most solutions just entirely flatten everything. This was popular on SO but yeah it flattens everything I want to be more selective

def flatten(lst):
 for elem in lst:
 if type(elem) in (tuple, list):
 for i in flatten(elem):
 yield i
 else:
 yield elem

What I am thinking is that if for each list the sublist should be at index 1, so

[0][1]
[1][1]
[2][1]

for item in list:
 item[1] - somehow flatten.

Any Idea or pointer?

+1 vote

I have about 500 search queries, and about 52000 files in which I have to find all matches for each of the 500 queries.

How should I approach this? Seems like the straightforward way to do it would be to loop through each of the files and go line by line comparing all the terms to the query, but this seems like it would take too long.

Can someone give me a suggestion as to how to minimize the search time?

...