To add all the values of a specific subkey for a dictionary python -
so consider 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 want sum "count"
"cities"
output have same value "no. of visits"
, asking question not context. using python2.7
well iterating values when realized might need value of "no. of visits"
out using it(it might not there every key).
for mac in dic_data: cities = dic_data[mac]['cities'] most_visited = max(cities, key=lambda x: cities[x]['count'])
so trying know how can sum of "count" of "cities" each mac.i want sum_of_count = sum(something here)
gives output sum of count 10
first key , 24
second key.
you iterate through each mac address sum()
count
s find max()
. assuming data stored in variable data
, here 1 statement version:
max([sum([data[visit]["cities"][city]["count"] city in data[visit]["cities"]]) visit in data])
here loop version comments:
# list store total no. of visits of each mac address counts = [] mac in data: # variable keep track of number of visits in current mac address visits = 0 city in data[mac]["cities"]: visits += data[mac]["cities"][city]["count"] counts.append(visits) # highest number of visits print max(counts)
Comments
Post a Comment