assign a value of dictionary's key into a variable - python

I have the following code in Python:
def buildXmlUpdate(dfrom, roomId, ldays):
start_date_sard.text = dfrom
roomId = str(roomId)
room_id_sard.text = roomId
ldays = {'avail': str(), 'price': str()}
availability_in_data.text = ldays['avail']
price_in_data.text = ldays['price']
for n in ldays:
print (dfrom, roomId, ldays)
Now when running
buildXmlUpdate ('21/12/2015', 1, [{'avail': 1, 'price': 100}, {'avail': 3, 'price': 120}])
I get the following output
('21/12/2015', '1', {'avail': '', 'price': ''})
('21/12/2015', '1', {'avail': '', 'price': ''})
In other words:
('21/12/2015', '1', {'avail': 1, 'price': 100})
('21/12/2015', '1', {'avail': 3, 'price': 120})
As you see here, the dictionary avail and price keys are set to an empty string but I want to set them according to the ldays arguments in the method.
What am I doing wrong?

Solved:
def buildXmlUpdate(dfrom, roomId, ldays):
start_date_sard.text = dfrom
roomId = str(roomId)
room_id_sard.text = roomId
#ldays = {'avail': str(), 'price': str()}
#availability_in_data.text = ldays['avail']
#price_in_data.text = ldays['price']
for n in ldays:
print (dfrom, roomId, n)
#availability_in_data.text = get.ldays['avail']
#price_in_data.txt = get.ldays['price']
ldays[-1]['avail'] = str(ldays[-1]['avail'])
ldays[-1]['price'] =str(ldays[-1]['price'])
availability_in_data.text = ldays[-1]['avail']
price_in_data.text = ldays[-1]['price']
Thank you all!

Related

How can I filter the lists within the lists by ids python?

I am getting data like this. Deposits from lists in this data should not be in other lists. How can I filter this list like this. Incoming data does not always have a specific index, number of deposits or withdrawals.
fakeData = [
{
'withId': 1232131212312, 'withAmount': 500,
'deposits': [{'id': 12321312312, 'type': 'deposit', 'amount': 250, 'date': '15-05-22 - 17:00:00'}, {'id': 123213123112, 'type': 'deposit', 'amount': 500, 'date': '15-05-22 - 00:00:00'}]},
{
'withId': 12326571312312, 'withAmount': 130, 'deposits': [{'id': 12321312312, 'type': 'deposit', 'amount': 250, 'date': '15-05-22 - 17:00:00'}, {'id': 123213123112, 'type': 'deposit', 'amount': 500, 'date': '15-05-22 - 00:00:00'}]},
{
'withId': 12321356712312, 'withAmount': 120,
'deposits': [{'id': 123213123112, 'type': 'deposit', 'amount': 500, 'date': '15-05-22 - 00:00:00'}]
}
]
Try this
def filter_packet(packet: list):
def filter_deposits(deposits: list, stack: list):
# Remove already-seen deposit IDs
result = list(filter(lambda x: x['id'] not in stack, deposits))
# Add the IDs to a stack
stack.extend([deposit['id'] for deposit in result])
return result
stack = []
filteredData = []
for packet in fakeData:
# Filter the deposits
new_deposits = filter_deposits(packet['deposits'], stack)
packet['deposits'] = new_deposits
filteredData.append(packet)
return filteredData

Filling in the list of the required format in the python loop

I am trying to create a list structure in a loop:
[children:[{text: "Title 1", id: '1', expanded: true,children: [{text: "title2", leaf: true ,},{text: "title3", leaf: true}]},{text: "Title4", id: '4', expanded: true, children: [{text: "title5", leaf: true,} ]}]]
The source data looks like this:
mylist =[{'id': '1', 'name': 'Title1', 'id_parent': '0'}, {'id': '2', 'name': 'title2', 'id_parent': '1'}, {'id': '3', 'name': 'title3', 'id_parent': '1'}, {'id': '4', 'name': 'Title4', 'id_parent': '0'}, {'id': '5', 'name': 'title5', 'id_parent': '4'}]
Using recursion, I go through the data and get parental and childish records:
def get_parent(id_parent):
c = []
for x in mylist:
if not x["id"] == id_parent and x["id_parent"] == id_parent:
if x["id_parent"] == id_parent:
x['expanded'] = True
else:
x['leaf'] = True
c.append(x)
return(c)
def get_tree(t):
lst = []
main_data = []
for x in get_parent(t):
all_stor = {}
all_stor["text"] = x['name']
all_stor["id"] = x['id']
if x.get('expanded'):
all_stor["expanded"] = x['expanded']
else:
all_stor["leaf"] = x['leaf']
main_data.append(all_stor)
lst.append([main_data, get_tree(x["id"])])
return lst
main = get_tree("0")
print(main)
How to fill the main_data list in a loop in order to get the necessary structure?
Your expected output should be a list of children from the root level:
def get_tree(l, parent='0'):
children = []
for d in l:
if d['id_parent'] == parent:
details = {'text': d['name'], 'id': d['id']}
grand_children = get_tree(l, d['id'])
if grand_children:
details.update({'expanded': True, 'children': grand_children})
else:
details['leaf'] = True
children.append(details)
return children
so that with your sample input, get_tree(mylist) would return:
[{'text': 'Title1', 'id': '1', 'expanded': True, 'children': [{'text': 'title2', 'id': '2', 'leaf': True}, {'text': 'title3', 'id': '3', 'leaf': True}]}, {'text': 'Title4', 'id': '4', 'expanded': True, 'children': [{'text': 'title5', 'id': '5', 'leaf': True}]}

how do I build a dictionary data inside a list?

I have this program:
def file(fname):
lines = open(fname).read().splitlines()
return(lines)
print(file('venue.txt'))
And it came out like this which I change into list:
['room 1, 10, 250']
How do I build a dictionary data with it, so that it can be like this:
[{'name': 'room 1', 'max': 10, 'cost': 250}]
Some clue maybe for me to build it.
Thanks
Edited:
def file(fname):
lines = open(fname).read().splitlines()
new = []
for i in lines:
split = i.split(', ')
new.append({'name':split[0],'max':split[1],'cost':split[2]})
return(new)
print(file('venue.txt'))
It prints:
new.append({'name':split[0],'max':split[1],'cost':split[2]})
IndexError: list index out of range
What does it mean?
You can try this:
import re
def file(fname):
lines = open(fname).read().splitlines()
return(lines)
headers = ["name", "max", "cost"]
data1 = [re.split(",\s+", i) for i in file("venue.txt")]
final_data = [{a:b for a, b in zip(headers, data} for data in data1]
print(final_data)
If they are separated by ', ' you can use the split() on ', '.
Will return an array with the separated items.
For your example:
current_list = ['room 1, 10, 250']
split = current_list[0].split(', ')
new_list = [{'name': split[0], 'max': int(split[1]), 'cost': int(split[2])}]
print(new_list)
output:
[{'name': 'room 1', 'max': 10, 'cost': 250}]
For a larger list:
current_list = ['room 1, 10, 250', 'room 2, 30, 500','room 3, 50, 850']
new_list = []
for i in current_list:
split = i.split(', ')
new_list.append({'name': split[0], 'max': int(split[1]), 'cost': int(split[2])})
print(new_list)
output:
[{'name': 'room 1', 'max': 10, 'cost': 250}, {'name': 'room 2', 'max': 30, 'cost': 500}, {'name': 'room 3', 'max': 50, 'cost': 850}]

Python sort a list by value of a dict inside the list

I have a List and inside the list i got a dict and i want to sort the list by a value of the dict.
How does this work?
[{'id': 0, 'thread': 'First',
'post': [
{'id': 0, 'title': 'MyPost', 'time': '2015-11-07 01:06:08.939687'}]
},
{'id': 1, 'thread': 'Second',
'post': [
{'id': 0, 'title': 'MyPost', 'time': '2015-11-07 01:06:42.933263'}]},
{'id': 2, 'name': 'NoPosts', 'post': []}]
I would like to sort my Threadlist by time of the first post, is that possible?
You can pass sort or sorted a key function:
In [11]: def key(x):
try:
return x["post"][0]["time"] # return ISO date string
except IndexError:
return "Not a date string" # any letter > all date strings
In [12]: sorted(d, key=key)
Out[12]:
[{'id': 0,
'post': [{'id': 0, 'time': '2015-11-07 01:06:08.939687', 'title': 'MyPost'}],
'thread': 'First'},
{'id': 1,
'post': [{'id': 0, 'time': '2015-11-07 01:06:42.933263', 'title': 'MyPost'}],
'thread': 'Second'},
{'id': 2, 'name': 'NoPosts', 'post': []}]

How to call a python class function from another file

I have this class in my parser.py file
class HostInfo(object):
def __init__(self, host_id):
self.osclass = []
self.osmatch = []
self.osfingerprint = []
self.portused = []
self.ports = []
self.extraports = []
self.tcpsequence = {}
self.hostnames = []
self.tcptssequence = {}
self.ipidsequence = {}
self.trace = {'port': '', 'proto': '', 'hop': []}
self.status = {}
self.address = []
self.hostscript = []
# Umit extension
self.id = host_id
self.comment = ''
# XXX this structure it not being used yet.
self.nmap_host = {
'status': {'state': '', 'reason': ''},
'smurf': {'responses': ''},
'times': {'to': '', 'srtt': '', 'rttvar': ''},
'hostscript': [],
'distance': {'value': ''},
'trace': {'port': '', 'proto': '', 'hop': []},
'address': [],
'hostnames': [],
'ports': [],
'uptime': {'seconds': '', 'lastboot': ''},
'tcpsequence': {'index': '', 'values': '', 'class': ''},
'tcptssequence': {'values': '', 'class': ''},
'ipidsequence': {'values': '', 'class': ''},
'os': {}
}
after that it defined a function which trying to find an host id from a xml file
def get_id(self):
try:
return self._id
except AttributeError:
raise Exception("Id is not set yet.")
def set_id(self, host_id):
try:
self._id = int(host_id)
except (TypeError, ValueError):
raise Exception("Invalid id! It must represent an integer, "
"received %r" % host_id)
Now i want to use call this get_id function from an another file.I tried so many time but it shows an error i.e. module can't be import
from parser import HostInfo
obj = HostInfo(<whatever host_id you need here>)
obj.get_id
this is the way, how are you actually doing it?

Categories