Python miminum value in dictionary of lists

前端 未结 3 895
情书的邮戳
情书的邮戳 2021-01-21 05:41

Sorry about the question repost...I should have just edited this question in the first place. Flagged the new one for the mods. Sorry for the trouble

Had to re-write the

3条回答
  •  灰色年华
    2021-01-21 06:22

    You can use min() with a key= argument, and specify a key function that compares the way you want.

    d = {'a': ['1'], 'b': ['1', '2'], 'c': ['2'], 'd':['1']}
    
    min_value = min(d.values())
    min_list = [key for key, value in d.items() if value == min_value]
    max_len = len(max(d.values(), key=len))
    long_list = [key for key, value in d.items() if len(value) == max_len]
    
    print(min_list)
    print(long_list)
    

    Notes:

    0) Don't use dict as a variable name; that's the name of the class for dictionary, and if you use it as a variable name you "shadow" it. I just used d for the name here.

    1) min_value was easy; no need to use a key= function.

    2) max_len uses a key= function, len(), to find the longest value.

提交回复
热议问题