[Python] Some Randoms

A few simple Python randoms. Not particularly complicated, but still takes time to get the syntax correct.

1) Counting hosts without . in name vs those without

c1 = 0; c2 = 0
for h in hosts:
  if len(h['name'].split(".")) > 1: c1 += 1
  else: c2 += 1

print('With dots = {0}, and without = {1}'.format(str(c1),str(c2)))


2) Output of hosts with . in name

for h in hosts:
  if len(h['name'].split(".")) > 1:
    print(h['name'])


3) Output of hosts with . in name but not ending in .something

for h in hosts:
  s = h['name'].split(".")
  if len(s) > 1 and s[-1].lower() != "something":
    print(h['name'])


4) Creating a List of VMs and Hosts and Checking for Uniqueness

ci = []
for i in vms:
  if len(i['name'].split(".")) == 1:
    ci += [i['name']]

len(ci)
len(ci) - len(set(ci))

for i in hosts:
  ci += [i['name'].split(".")[0]]

len(ci)
len(ci) - len(set(ci))


5) Dumping JSON (i.e. from requests) output into a text file

import json
open('C:\\LOGS\\dump.txt', 'w').write(json.dumps())

Note: Usually use json.loads(r.text) or similar to get requests output.

Comments