ranadan ranadan - 5 months ago 15
Python Question

python - Getting key with second and third maximum value in dictionary

I have a JSON file something like this.

{
"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"}
}
}
}


Now to get the max visited city by a user or the key
b0:47:bf:af:c1:42
for each key I am currently parsing it into a dict and then using this.

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


But how to get second max visited city, third max visited city and so on. I am using python 2.7.

Answer

Instead of using max, you can use sorted.

That way you will get a sorted list based on 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']

UPDATE To get the output you asked in the comments:

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']}
Comments