python - 获取字典中第二个和第三个最大值的键

时间:2016-06-30 06:36:13

标签: python python-2.7 dictionary

我有一个像这样的JSON文件。

{
"b0:47:bf:af:c1:42": 
 {
 "No. of visits": 10, "cities": 
    {
      "Mumbai": {"count": 5,"last_visited": "5/22/2016"},
      "Kolkata": {"count": 2,"last_visited": "5/22/2016"},
      "Amritsar":{"count": 3,"last_visited": "5/22/2016"}
     }
},
"c0:ee:fb:71:be:0d": 
 {
 "No. of visits": 24, "cities": 
 {
  "Mumbai": {"count": 2,"last_visited": "5/22/2016"},
  "Kolkata": {"count": 20,"last_visited": "5/22/2016"},
  "Amritsar":{"count": 2,"last_visited": "5/22/2016"}
 }
}
}

现在要获取用户的最大访问城市数或每个密钥b0:47:bf:af:c1:42,我正在将其解析为dict然后使用它。

for mac in dic_data:
    cities = dic_data[mac]['cities']
    most_visited_city = max(cities, key=lambda x: cities[x]['count'])

但如何获得第二个最大访问城市,第三个最大访问城市等等。我使用的是python 2.7。

1 个答案:

答案 0 :(得分:2)

您可以使用max,而不是使用sorted

通过这种方式,您将获得基于count的排序列表:

d = {
"b0:47:bf:af:c1:42":
 {
 "No. of visits": 10, "cities":
    {
      "Mumbai": {"count": 5,"last_visited": "5/22/2016"},
      "Kolkata": {"count": 2,"last_visited": "5/22/2016"},
      "Amritsar":{"count": 3,"last_visited": "5/22/2016"}
     }
},
"c0:ee:fb:71:be:0d":
 {
 "No. of visits": 24, "cities":
 {
  "Mumbai": {"count": 2,"last_visited": "5/22/2016"},
  "Kolkata": {"count": 20,"last_visited": "5/22/2016"},
  "Amritsar":{"count": 2,"last_visited": "5/22/2016"}
 }
}
}

for mac in d:
    cities = d[mac]['cities']

    sorted_cities = sorted(cities, key=lambda x: cities[x]['count'])
    # or if you want the sort to be the other way around
    reversed_sorted_cities = sorted(cities, key=lambda x: cities[x]['count'],
                                    reverse=True)
    print sorted_cities


>> ['Kolkata', 'Amritsar', 'Mumbai']
   ['Amritsar', 'Mumbai', 'Kolkata']

更新要获得评论中提出的输出:

d = { ... }

info = {}

for mac in d:
    cities = d[mac]['cities']

    info[mac] = sorted(cities, key=lambda x: cities[x]['count'])

print info

>> {'b0:47:bf:af:c1:42': ['Kolkata', 'Amritsar', 'Mumbai'],  
    'c0:ee:fb:71:be:0d': ['Mumbai', 'Amritsar', 'Kolkata']}

也可以使用字典理解在一行中完成:

info = {mac: sorted(d[mac]['cities'], key=lambda x: d[mac]['cities'][x]['count']) 
        for mac in d}