I have a python function that calls an API, and the response is a massive json which 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.
CodePudding user response:
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()] )
CodePudding user response:
You need to use the set()
function to count servers:
print(len(set(dict.keys())))