Finding the max value of list in dictionary

后端 未结 2 1096
遇见更好的自我
遇见更好的自我 2021-01-29 11:14

I have a dict and behind each key is a list stored. Looks like this:

dict with values:  {
u\'New_York\': [(u\'New_York\', u\'NY\', datetime.datetime(2014, 8, 13,         


        
2条回答
  •  孤独总比滥情好
    2021-01-29 11:38

    Can you have a look at : https://wiki.python.org/moin/HowTo/Sorting#Sorting_Mini-HOW_TO

    The answer may be :

    In [2]: import datetime
    In [3]: d = {
    u'New_York': [(u'New_York', u'NY', datetime.datetime(2014, 8, 13, 0, 0), 10),         (u'New_York', u'NY', datetime.datetime(2014, 8, 13, 0, 0), 4), (u'New_York', u'NY', datetime.datetime(2014, 8, 13, 0, 0), 3)], 
    u'Jersy': [(u'Jersy', u'JY', datetime.datetime(2014, 8, 13, 0, 0), 6), (u'Jersy', u'JY', datetime.datetime(2014, 8, 13, 0, 0), 7)], 
    u'Alameda': [(u'Alameda', u'CA', datetime.datetime(2014, 8, 13, 0, 0), 1), (u'Alameda', u'CA', datetime.datetime(2014, 8, 13, 0, 0), 2), (u'Alameda', u'CA', datetime.datetime(2014, 8, 13, 0, 0), 3), (u'Alameda', u'CA', datetime.datetime(2014, 8, 13, 0, 0), 1)]
    }
    In [4]: def give_max_values(d):
    ...:     res = {}
    ...:     for key, vals in d.iteritems():
    ...:         res[key] = max(vals, key=lambda x: x[3])
    ...:     return res
    In [5]: somedic = give_max_values(d)
    In [6]: print somedic
    {u'New_York': (u'New_York', u'NY', datetime.datetime(2014, 8, 13, 0, 0), 10), u'Jersy': (u'Jersy', u'JY', datetime.datetime(2014, 8, 13, 0, 0), 7), u'Alameda': (u'Alameda', u'CA', datetime.datetime(2014, 8, 13, 0, 0), 3)}
    

提交回复
热议问题