How to convert Double dict from file and use it - python

I have double dict which i want read using json, but i don't really know how. Im running Python 3
{ "www.svetaine.lt":{ "true": "111.111.222.11" }}
{ "www.svetaine2.lt":{ "true": "111.111.222.11" }}
I know only how to make simple dict
def openfile():
data = []
d={}
with open('test.json', 'r') as f:
for line in f:
data.append(json.loads(line))
for item in data:
d.update(item)
f.close()
return d
So I would like to improve my code by using double dict.
P.S Could you also mention how I could mention refer to it after reading like
for ele in d:
getname="www.svetaine.lt"
getstatus="true"
getip= "111.111.222.11"

import json
def openfile():
d={}
with open('s.json', 'r') as f:
for line in f:
line_ = json.loads(line)
name = line_.keys()[0]
status = line_[name].keys()[0]
ip = line_[name][status]
d[name] = {'name':name, 'status':status, 'ip':ip}
f.close()
return d
data = openfile()
# print whole dict
for ele in data:
print ele, data[ele]
# retrieving info w.r.t name
print data['www.svetaine.lt']

Related

Python looping through files and saving content to dict

I have the following code:
import os
import json
import ipaddress
iplist = []
ipiflist = []
mydict = {}
for filename in os.listdir('data/'):
with open(os.path.join('data/', filename), 'r') as f:
data = json.load(f)
mydict.update(data)
print(mydict)
In the data directory there are several JSON files that I open in this loop.
I update the dict in every loop and for this reason I get the following output:
{'ipif_1001': '10.10.160.129', 'ipif_1002': '10.10.160.142', 'ipif_1003': '10.10.160.169', 'ipif_1004': '10.10.160.173', 'ipif_3334': '10.10.160.194', 'IpIf3337': '10.10.160.126'}
{'ipif_1001': '10.10.160.129', 'ipif_1002': '10.10.160.142', 'ipif_1003': '10.10.160.170', 'ipif_1004': '10.10.160.174', 'ipif_3334': '10.10.160.194', 'IpIf3337': '10.10.160.126', 'ipif_1005': '10.10.160.178', 'ipif_1006': '10.10.160.182'}
{'ipif_1001': '10.10.160.129', 'ipif_1002': '10.10.160.142', 'ipif_1003': '10.10.160.170', 'ipif_1004': '10.10.160.174', 'ipif_3334': '10.10.160.194', 'IpIf3337': '10.10.160.126', 'ipif_1005': '10.10.160.178', 'ipif_1006': '10.10.160.182', 'IpIf1001': '10.10.160.138', 'IpIf1002': '10.10.160.141', 'IpIf1003': '10.10.160.153', 'IpIf1006': '10.10.160.181', 'IpIf_CPEDCN': '10.10.160.241', 'IpIf_DCNMgt': '10.10.191.253', 'ipif1164': '10.10.160.166', 'IpIf1010': '10.10.170.1'}
I only need the summarized output from the last loop. How can I only access this?
Thanks for your help
The for loop in python has an else statement, which will only be executed when the loop was successful. Thus there you can plot your last resut?
for filename in os.listdir('data/'):
with open(os.path.join('data/', filename), 'r') as f:
data = json.load(f)
mydict.update(data)
else:
print(mydict)
import os
import json
import ipaddress
iplist = []
ipiflist = []
mydict = {}
list = os.listdir('data/')
for filename in os.listdir('data/'):
with open(os.path.join('data/', filename), 'r') as f:
data = json.load(f)
if list[list.count-1] == filename: #check last filename in the directory with the current filename in the loop
mydict.update(data)
print(mydict)
Try it like this

how to read json file without using json libarary or without any other libarary in to dictionary or list?

I have a JSON file and i need to read it into dictionary or list without using and library.This is my file content.
{
"101":"Break and Enter Commercial",
"102":"Break and Enter Residential/Other",
"103":"Vehicle Collision or Pedestrian Struck (with Fatality)",
"104":"Vehicle Collision or Pedestrian Struck (with Injury)"
}
This is what i try
def read_codes(filename):
jsonData = {}
# empty list to append to it later
file = open(filename, "r")
for key in file:
print(key)
return jsonData
print(read_codes('codes.json'))
What about such way:
with open(file) as f:
your_dict = eval(f.read().replace('\n', ''))
You could open it as a text file. It would return you list, then filter the list as you require.
with open('file.json', 'r') as jsonFile:
json_obj = jsonFile.readlines()
json_obj = [(obj.rstrip()).lstrip()[:-1] for obj in json_obj[1:-1]]
print(json_obj)

yaml.dump is dumping in a dict, and I don't want it to do that

I was trying to make a tool that updates yaml values in files that have "PENDING" in them. It does work, but I need it to be formatted like this:
fields:
setName: ("name")
WishName: ("name")
WishNameState: ("PENDING")
However, it wants to dump it in this format:
fields: {WishName: ("name"), WishNameState: ("APPROVED"), setName: ("name")}
How can I make it dump in the format I want it to?
Here's my code, so you know how I'm currently doing it:
import glob
import os
import yaml
def processFile(f,t):
data = open(f,'rb').read()
lines = data.replace('\r\n','\n').split('\n')
lines_found = []
for i,x in enumerate(lines):
if t in x:
lines_found.append(i+1)
return lines_found
term = 'PENDING'
for x in glob.glob('*.yaml'):
r = processFile(x,term)
if r:
with open(x) as f:
yamlfile = yaml.load(f)
fields = yamlfile['fields']
name = fields['WishName']
print('Name: ' + name)
print('Approve or reject?')
aor = raw_input('a/r: ')
if aor == 'a':
fields['setName'] = name
fields['WishNameState'] = '("APPROVED")'
with open(x, "w") as f:
yaml.dump(yamlfile, f)
elif aor == 'r':
fields['WishNameState'] = '("REJECTED")'
with open(x, "w") as f:
yaml.dump(yamlfile, f)
else:
'Invalid response. Shutting down...'
sys.exit()
print('End of results!')
Any and all help is appreciated! Thanks :)
In your code, replace
yaml.dump(yamlfile, f)
with
yaml.dump(yamlfile, f, default_flow_style=False)

Python: How to add content of file to list from position

I have a JSON file containing various objects each containing elements. With my python script, I only keep the objects I want, and then put the elements I want in a list. But the element has a prefix, which I'd like to suppress form the list.
The post-script JSON looks like that:
{
"ip_prefix": "184.72.128.0/17",
"region": "us-east-1",
"service": "EC2"
}
The "IP/mask" is what I'd like to keep. The List looks like that:
'"ip_prefix": "23.20.0.0/14",'
So what can I do to only keep "23.20.0.0/14" in the list?
Here is the code:
json_data = open(jsonsourcefile)
data = json.load(json_data)
print (destfile)
d=[]
for objects in (data['prefixes']):
if servicerequired in json.dumps(objects):
#print(json.dumps(objects, sort_keys=True, indent=4))
with open(destfile, 'a') as file:
file.write(json.dumps(objects, sort_keys=True, indent=4 ))
with open(destfile, 'r') as reads:
liste = list()
for strip in reads:
if "ip_prefix" in strip:
strip = strip.strip()
liste.append(strip)
print(liste)
Thanks,
dersoi
Ok so i've went through your JSON object
import json, urllib2
url = 'https://ip-ranges.amazonaws.com/ip-ranges.json'
req = urllib2.Request(url)
res = urllib2.urlopen(req)
j = json.load(res)
print j['prefixes'][0]['ip_prefix']
prefixes = j['prefixes']
for i in prefixes:
print i['ip_prefix']
the result:
>>>
23.20.0.0/14
23.20.0.0/14
27.0.0.0/22
43.250.192.0/24
43.250.193.0/24
46.51.128.0/18
46.51.192.0/20
46.51.216.0/21
46.51.224.0/19
etc...
So now you want all into one txt file right?
So you do this:
import json, urllib2
url = 'https://ip-ranges.amazonaws.com/ip-ranges.json'
req = urllib2.Request(url)
res = urllib2.urlopen(req)
j = json.load(res)
#print j['prefixes'][0]['ip_prefix']
prefixes = j['prefixes']
destfile = 'destfile.txt'
with open('destfile.txt', 'w') as f:
for i in prefixes:
#print i['ip_prefix']
f.write(i['ip_prefix'])
f.write('\n')
f.close
Best regards,
Rizzit
I've refactored your code, try this out:
import json
with open('sample.json', 'r') as data:
json_data = json.loads(data.read())
print json_data.get('ip_prefix')
# Output: "184.72.128.0/17"
You can rewrite the second open block as:
with open(destfile, 'r') as reads:
data = json.load(reads)
liste = [i['ip_prefix'] for i in data]
Although, I don't think you need to write to an intermediate file anyway, you could combine both blocks.

Save/load function in Python

I have to create a save function and a load function that saves a dictionary in the format of:
123;Kalle;
123;Maria;
321;Anna;
321;Olle;
My dictionary is supposed to look like a phonebook, with the key being the name and the value is the phonenumber:
telebook = {"jacob":"8472923777", "nisse":"092563243"}
How can I write a function that saves my phonebook in the format mentioned? It should look like this:
8472923777;jacob;
This is my current code:
def save(lista, telebook):
import pickle
filename = lista[1]
f = open(filename, "w")
pickle.dump(telebook, f)
f.close()
print telebook
def load(lista, telebook):
import pickle
try:
filename = lista[1]
f = open(filename, "r")
telebook_1 = pickle.load( f )
telebook.clear()
telebook.update(telebook_1)
f.close()
print telebook
except:
print "This file doesn't exist"
EDIT:
My save function was easier than I thought, managed to solve it on my own. Not sure how to get the load function to work though.
book = raw_input("telebook> ").lower()
lista = book.split()
def save(lista, telebook):
filename = lista[1]
f = open(filename, "w")
for name, num in telebook.items():
f.write(num+";"+name+";"+"\n")
f.close()
print telebook
My load is the same as before but obviously I can't use that one anymore.
def save(telebok, filepath):
with open(filepath, 'w') as outfile:
for name,num in telebok.items():
outfile.write("{};{};\n".format(num, name))
And to get it back:
import csv
def load(filepath):
with open(filepath) as infile:
telebok = dict((v,k) for v,k,_ in csv.reader(infile, delimiter=';'))
return telebok

Categories