convert variables into dictonaries - python

I have something like this where trade_date, effective_date and termination_date are date values:
tradedates = dict(((k, k.strftime('%Y-%m-%d'))
for k in (trade_date,effective_date,termination_date)))
I get this:
{datetime.date(2005, 7, 25): '2005-07-25',
datetime.datetime(2005, 7, 27, 11, 26, 38): '2005-07-27',
datetime.datetime(2010, 7, 26, 11, 26, 38): '2010-07-26'}
What I would like is:
{'trade_date':'2005-07-25','effective_date':'2005-07-27','termination_date':'2010-07-26'}
How do I achieve this?

Using vars:
>>> import datetime
>>>
>>> trade_date = datetime.date(2005, 7, 25)
>>> effective_date = datetime.datetime(2005, 7, 27, 11, 26, 38)
>>> termination_date = datetime.datetime(2010, 7, 26, 11, 26, 38)
>>>
>>> d = vars() # You can access the variable as d['name']
>>> tradedates = {
... name: d[name].strftime('%Y-%m-%d')
... for name in ('trade_date', 'effective_date', 'termination_date')
... }
>>> tradedates
{'effective_date': '2005-07-27', 'termination_date': '2010-07-26', 'trade_date': '2005-07-25'}

For something that size, I'd create the dict directly:
result = {
'trade_date': format(trade_date, '%Y-%m-%d'),
'effective_date': format(effective_date, '%Y-%m-%d'),
# etc....
}

I am not sure if I got your question right. But let me explain what I understood and my answer for that:
You know the variable names: trade_date,effective_date,termination_date
And they have data in them
You could easily do:
tradedates = dict()
for k in ('trade_date','effective_date','termination_date'):
tradedates[k] = eval(k).strftime('%Y-%m-%d') // eval will evaluate them as a variable name not as a string.
This will give you a final dict something like:
{
'trade_date': <date_string_according_to_the_format_above>
'effective_date': <date_string_according_to_the_format_above>
'termination_date': <date_string_according_to_the_format_above>
}

Related

django error: "asc() got an unexpected keyword argument 'nulls_last' "

class CustomOrderFilter(OrderingFilter):
allowed_custom_filters = ['target_item__type_service', 'target_item__level', 'target_item__room__name',
'client__user_full_name', 'designer__user_full_name', 'status', 'date_due_decorist',
'target_item__date_answered']
def get_ordering(self, request, queryset, view):
params = request.query_params.get(self.ordering_param)
if params:
fields = [param.strip() for param in params.split(',')]
ordering = [f for f in fields if f.lstrip('-') in self.allowed_custom_filters]
if ordering:
return ordering
return self.get_default_ordering(view)
def filter_queryset(self, request, queryset, view):
order_fields = []
ordering = self.get_ordering(request, queryset, view)
if not ordering:
return queryset
order_fields.append(ordering[0])
if 'status' in order_fields or '-status' in order_fields:
ids = [0, 1, 2, 18, 3, 6, 9, 7, 21, 5, 8, 11, 12, 10, 14, 15, 16, 20, 4, 13, 17]
rev_ids = [11, 8, 5, 21, 7, 9, 6, 3, 18, 2, 1, 0, 12, 10, 14, 15, 16, 20, 4, 13, 17]
if '-status' in order_fields:
order = Case(*[When(status=id, then=pos) for pos, id in enumerate(rev_ids)])
else:
order = Case(*[When(status=id, then=pos) for pos, id in enumerate(ids)])
return queryset.order_by(order)
if '-date_due_decorist' in order_fields:
return queryset.order_by(F('date_due_decorist').desc(nulls_last=True))
elif 'date_due_decorist' in order_fields:
return queryset.order_by(F('date_due_decorist').asc(nulls_last=True))
return queryset.order_by(ordering[0])
In custom ordering django, I am getting error as "asc() got an unexpected keyword argument 'nulls_last' ". I want to show null values always at last in date_due_decorist column while sorting. Please let me know if django version 1.10 supports 'nulls_last' or not.
If not support then let me know how can this be done?

Printing error with python class attributes, where have I gone wrong?

I'm trying to print a select row and columns from a spreadsheet, however when I call on the spreadsheet dataframe attribute it fails to print state that the name dataframe is not defined. where have I gone wrong?
import pandas
class spreadsheet:
def __init__(self, location, dataframe, column, rows):
self.location = ('Readfrom.xlsx')
self.dataframe = pandas.read_excel(location)
self.column = 2
self.rows = 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 27, 28, 29
a = dataframe.iloc[column,[rows]]
print(a)
You should instantiate an object from the Spreadsheet class and then access the attribute of the instance. You can learn more about Object-Oriented Programming in Python here.
I think that what you want to do in your code is something like the code below.
import pandas
class Spreadsheet:
def __init__(self, location):
self.location = location
self.dataframe = pandas.read_excel(location)
sp = Spreadsheet(location="Readfrom.xlsx")
rows = [4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 27, 28, 29]
a = sp.dataframe.iloc[rows, 2]
print(a)
I think you have an indentation problem.
Your dataframe is a parameter of your spreadsheet constructor method and you try to access it even from outside the class.
To access the dataframe variable u have to move your code a = dataframe.iloc[column,[rows]] inside your __init__ method or you need to create a spreadsheet object first and access it via this object.
EDIT:
On second thoughts i think you should check out the basics how to use classes in Python.
You don't use the parameters of the __init__ so why du you have them?
dataframe is only accessible by a spreadsheet object
This code should fix your problem but i recommend to go through some basic tutorials to understand how exactly classes and objects are working:
import pandas
class spreadsheet:
def __init__(self):
self.location = ('Readfrom.xlsx')
self.dataframe = pandas.read_excel(self.location)
self.column = 2
self.rows = 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 27, 28, 29
s = spreadsheet()
a = s.dataframe.iloc[s.column,[s.rows]]
print(a)

SQLAlchemy _asdict() method returns only one column

I am trying to convert the rows returned in a SQLAlchemy query to dictionaries. When I try to use the ._asdict() method, I am only getting a key-value pair for the first column in my results.
Is there something else I should do to create a key-value pair in the dictionary for all columns in the result row?
class Project(db.Model):
__tablename__ = 'entries'
id = db.Column(db.Integer, primary_key=True)
time_start = db.Column(db.DateTime(timezone=False))
time_end = db.Column(db.DateTime(timezone=False))
name = db.Column(db.String(256), nullable=True)
analyst = db.Column(db.String(256), nullable=True)
def __init__(id, time_start, time_end, project_name, analyst):
self.id = id
self.time_start = time_start
self.time_end = time_end
self.name = name
self.analyst = analyst
latest_projects = db.session.query((func.max(Project.time_end)), Project.analyst).group_by(Project.analyst)
for row in latest_projects.all():
print (row._asdict())
{'analyst': 'Bob'}
{'analyst': 'Jane'}
{'analyst': 'Fred'}
I was expecting to see results like this...
{'analyst': 'Bob', 'time_end': '(2018, 11, 21, 14, 55)'}
{'analyst': 'Jane', 'time_end': '(2017, 10, 21, 08, 00)'}
{'analyst': 'Fred', 'time_end': '(2016, 09, 06, 01, 35)'}
You haven't named the func.max() column, so there is no name to use as a key in the resulting dictionary. Aggregate function columns are not automatically named, even when aggregating a single column; that you based that column on on the time_end column doesn't matter here.
Give that column a label:
latest_projects = db.session.query(
func.max(Project.time_end).label('time_end'),
Project.analyst
).group_by(Project.analyst)
Demo:
>>> latest_projects = db.session.query(
... func.max(Project.time_end).label('time_end'),
... Project.analyst
... ).group_by(Project.analyst)
>>> for row in latest_projects.all():
... print (row._asdict())
...
{'time_end': datetime.datetime(2018, 11, 21, 14, 55), 'analyst': 'Bob'}
{'time_end': datetime.datetime(2016, 9, 6, 1, 35), 'analyst': 'Fred'}
{'time_end': datetime.datetime(2017, 10, 21, 8, 0), 'analyst': 'Jane'}

MyHDL free variables

Whenever I try to call this function in the MyHDL implementation of MD5 I've been working on I get this error:
File "/usr/local/lib/python2.7/dist-packages/myhdl/conversion/_misc.py", line 149, in raiseError
raise ConversionError(kind, msg, info)
myhdl.ConversionError: in file MD5-8, line 85:
Free variable should be a Signal or an int: calculate
Here is the entire script. If anyone has any light to shed on this or anything else that would be extremely helpful.
Thanks so much.
from myhdl import *
def operative(M0,M1,M2,M3,M4,M5,M6,M7,M8,M9,M10,M11,M12,M13,M14,M15,enable,clock):
singletick = 0
def toW32(x):
return(modbv(x, min=0, max=2**32)[32:])
def leftrotate(x, c):
return ((x<<c) | (x>>(32-c)) % (2**32))
def calculate(M, A, B, C, D, count):
KCONTENT = (0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee,0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8, 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391)
SCONTENT = (7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21)
F = int(0)
G = int(0)
#get G and F
if(count<=15):
if(count >=0):
F= (B&C)|((~B)&D)
G = int(count)
elif(count<=31):
if(count >= 15):
F = (D&B)|((~D)&C)
G = int(5*count +1) % 16
elif(count<=47):
if(count>=32):
F = (B^C^D)
G = int(3*count+5) % 16
elif(count <= 63):
if(count >= 48):
F = C^(B|(~D))
G = int(7*count) % 16
#swapping A through D and then calling again
temp = D
D = C
C = B
F = toW32(F)
G = toW32(G)
currentM = toW32(int(M[G]))
currentK = toW32(int(KCONTENT[count]))
currentS = toW32(int(SCONTENT[count]))
#B = leftrotate((((A + F) % (2**32) + (M[G]+KCONTENT[count]) % (2**32)) % (2**32)), SCONTENT[count])
A2 = toW32(A)
F2 = toW32(F)
bcomp0 = toW32((A2 + F2) % (2**32))
bcomp1 = toW32((currentM + currentK) % (2**32))
bcomp = toW32((bcomp0 + bcomp1) % (2**32))
bcomp2 = (leftrotate(bcomp, currentS))
B = toW32((B + bcomp2) % (2**32))
A = temp
print(B)
if(count>=63):
outA = (toW32((0x67452301+A) % (2**32)))
outB = (toW32((0xefcdab89+B) % (2**32)))
outC = (toW32((0x98badcfe+C) % (2**32)))
outD = (toW32((0x10325476+D) % (2**32)))
print(hex(concat(outA, outB, outC, outD)))
return(outA, outB, outC, outD)
else:
count = count + 1
calculate(M, A, B, C, D, count)
HALF_PERIOD = delay(10)
#always(HALF_PERIOD)
def clockGen():
clock.next = not clock
M = (M0,M1,M2,M3,M4,M5,M6,M7,M8,M9,M10,M11,M12,M13,M14,M15)
#always(clock.posedge)
def central():
if(enable == 1):
A = toW32(0x67452301)
B = toW32(0xefcdab89)
C = toW32(0x98badcfe)
D = toW32(0x10325476)
count = toW32(0)
final = int(0)
final = calculate(M, A, B, C, D, count)
return clockGen, central

Python convert string to list (No .split())

I've got a little problem:
I have a String in my Database which is called actions.
Now, I'm writing a method, which gets that string from the database
(that works), and then I want to turn that string into a list.
I know actions.split(), but this didn't work out so well for me, because if my string looks like this:
actions = [
{u'action': 'visit_testing', u'timestamp': datetime.datetime(2016, 2, 12, 13, 32, 14)},
{u'action': 'visit_foo', u'timestamp': datetime.datetime(2016, 2, 12, 13, 37, 50)}
]
I can't use actions.split(', ') because it would mess up the dictionaries inside.
Till now I've got the following code:
timestamp = datetime.now().replace(microsecond=0)
dict = {'timestamp': timestamp, 'action': action}
if self.actions:
actions_string = str(self.actions)
actions_stripped = actions_string.strip('[')
actions_stripped = actions_stripped.strip(']')
actions_splitted = actions_stripped.split(', ')
new_action_list = []
buffer = ''
for string in actions_splitted:
if '{' in string:
buffer = str(string)
elif '}' in string:
buffer = buffer + ', ' + str(string)
new_action_list.append(str(buffer))
buffer = ''
else:
buffer = buffer + ', ' + str(string)
self.actions = str(buffer)
self.last_action = datetime.now().replace(microsecond=0)
self.save()
else:
self.actions = '['+str(dict)+']'
self.last_action = datetime.now().replace(microsecond=0)
self.save()
Addition: If I run the method when actions is empty, it gives me a list with one dictionary, but if I run it when it already has something in it, if sets actions to "".
You should be using the json module to store valid JSON in your database. You can create a valid action list from that string using exec. But please beware that using exec or eval is a potentially dangerous practice.
import datetime
stuff = '''
actions = [{u'action': 'visit_testing', u'timestamp': datetime.datetime(2016, 2, 12, 13, 32, 14)}, {u'action': 'visit_foo', u'timestamp': datetime.datetime(2016, 2, 12, 13, 37, 50)}]
'''
exec(stuff)
print(actions)
print(actions[0]['timestamp'])
output
[{u'action': 'visit_testing', u'timestamp': datetime.datetime(2016, 2, 12, 13, 32, 14)}, {u'action': 'visit_foo', u'timestamp': datetime.datetime(2016, 2, 12, 13, 37, 50)}]
2016-02-12 13:32:14
Use json library.
import json
my_dict_or_list = json.loads(your_string)
then work with Python objects. You will gain so much time :-D
I found a way that works for me:
timestamp = datetime.datetime.now().replace(microsecond=0)
if self.actions:
new_dict = {"timestamp": timestamp, "action": action}
#tmp_actions = json.loads(self.actions)
tmp_actions = self.actions
exec(tmp_actions)
actions.append(new_dict)
self.actions = str('actions = '+str(actions))
self.last_action = datetime.datetime.now().replace(microsecond=0)
self.save()
else:
exec('''actions = ['''+str({"timestamp": timestamp, "action": action})+''']''')
self.actions = 'actions = '+str(actions)
self.last_action = datetime.datetime.now().replace(microsecond=0)
self.save()
Thanks for all the help.

Categories