如何在Python中获取字典列表中键或值的最大长度

时间:2016-04-07 13:54:03

标签: python-3.x

我试图找到有序字典列表中最后一个键值对(在每个字典中)的最大长度。

示例:

# below is the list of ordered dict
my_list = [{'Table': 'Config', 'Column': 'config_id', 'DataType': 'int'},
       {'Table': 'Config', 'Column': 'config_name', 'DataType': 'varchar'},
       {'Table': 'Config', 'Column': 'config_value', 'DataType': 'numeric'}]
 # Expected out put
 Out put: 8 # as the key (in this case "DataType") has max chars  and if any value for the same key has max char then it will return that value.

任何建议!

1 个答案:

答案 0 :(得分:0)

鉴于my_list :: [collections.OrderedDict],以下工作。

kvs = (list(d.items())[-1] for d in my_list) # [(last_key1, last_val1),..]
words = [max(k,v,key=len) for k,v in kvs]    # [max_key1_val1, max_key2_val2,..]
chars = [len(word) for word in words]        # [len(max_key1_val1),...]
ans = max(chars)                             # max() of all

如果这不是您想要的,请在下面做评论。我会改进答案。