Reputation: 29
I have a python function that calls an API, and the response is a massive JSON that I store as a dictionary.
For the massive output I managed to cut I down to a new dictionary like this one
{'server-xx': '2'}
{'server-xy1': '0', 'server-xy2': '1'}
{'server-xz1': '0', 'server-xz2': '0'}
I'm interested in counting the total number of servers, in this case it's 5 "server-xx", "server-xy1", "server-xy2", "server-xz1", "server-xz2".
The number next to the server name is not important, I just need the total number of servers.
But I'm not sure how to do this. i know i can count the number of keys print(len(dict.keys()))
, but this will return 3 in my case.
How can I solve this? I need the value 5 as an it.
Upvotes: 1
Views: 615
Reputation: 5223
You need to use the set()
function to count servers:
print(len(set(dict.keys())))
Upvotes: 0
Reputation: 60
How is your dictionary built?
I'm guessing it's something like this -
dictionary = { "dict1" : {'server-xx': '2'},
"dict2" : {'server-xy1': '0', 'server-xy2': '1'},
"dict3" : {'server-xz1': '0', 'server-xz2': '0'} }
If it is you can do something like this -
count = sum( [len(d) for d in dictionary.values()] )
Upvotes: 1