user6429297
user6429297

Reputation:

To add all the values of a specific subkey for a dictionary python

so consider a dictionary.

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

so what i want is to sum all the "count" for all the "cities" my output will have the same value as "No. of visits", obviously I am asking the question not specifically for this context. I am using python2.7

well I was iterating to get some values when I realized I might need to get value of "No. of visits" with out using it(it might not be there for every key).

for mac in dic_data:

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

so I was just trying to know how can I get sum of "count" of all "cities" each mac.I just want sum_of_count = sum(something here) which gives output as sum of count 10 for first key and 24 for second key.

Upvotes: 0

Views: 595

Answers (1)

Moon Cheesez
Moon Cheesez

Reputation: 2701

You could just iterate through each mac address sum() the counts then find the max(). Assuming your data is stored in the variable data, here is the one statement version:

max([sum([data[visit]["cities"][city]["count"] for city in data[visit]["cities"]]) for visit in data])

Here is the for loop version with comments:

# This list will store all the total no. of visits of each mac address
counts = []
for mac in data:
    # This variable will keep track of the number of visits in the current mac address
    visits = 0
    for city in data[mac]["cities"]:
        visits += data[mac]["cities"][city]["count"]
    counts.append(visits)
# Get the highest number of visits
print max(counts)

Upvotes: 1

Related Questions