How Do I Access This A Value In A Python Data Dictionary? - python

I have a python data dictionary that I am using to do some date comparisions. However when I loop through it I can't figure out how to access the DailyPlannerRequest value. I have tried doing a request.DailyPlannerRequest but the error that comes back is 'datetime.date' object has no attribute 'DailyPlannerRequest'. I've read a bit about trying to convert this dictionary value but can't find anything helpful. I am trying to do a loop and query a filter value and compare it to this data dictionary value.
I'm trying to do something like....
if request.day == day and event.daily_planner_request_name == request.DailyPlannerRequest :
I've done this lots of times before but the complication here is that one is a queryset and the other is a dictionary value that I'm trying to get to compare.
I've played a bit with the approach documented here Accessing dict keys like an attribute?
But can't seem to figure this out.

#Waldemar Podsiadlo answered this one. The answer he provided helped me with my troubleshooting...for key, value in dict.items()

Related

Accessing Unicode Values in a Python Dictionary

I have a dictionary full of unicode keys/values due to importing JSON through json.loads().
dictionaryName = {u'keyName' : u'valueName'}
I'm trying to access values inside the dictionary as follows:
accessValueName = dictionaryName.get('keyName')
This returns None, assumedly because it is looking for the String 'keyName' and the list is full of unicode values. I tried sticking a 'u' in front of my keyName when making the call, but it still returns none.
accessValueName = dictionaryName.get(u'keyName')
I also found several seemingly outdated methods to convert the entire dictionary to string values instead of unicode, however, they did not work, and I am not sure that I need the entire thing converted.
How can I either convert the entire dictionary from Unicode to String or just access the values using the keyname?
EDIT:
I just realized that I was trying to access a value from a nested dictionary that I did not notice was nested.
The solution is indeed:
accessValueName = dictionaryName.get('keyName')
Dictionaries store values in a hash table using the hash values of the object.
print(hash(u"example"))
print(hash("example"))
Yields the same result. Therefore the same dictionary value should be accessible with both.

Accessing Nested Dictionary - Python

I have below Dictionary those values I am pulling from aws S3 bucket -
{u'Policy': u'{"Version":"2012-10-17","Statement":[{"Sid":"AddPerm","Effect":"Allow","Principal":"*","Action":"s3:GetObject","Resource":"arn:aws:s3:::elliemaetestbucket1/*"},{"Sid":"AddPerm1","Effect":"Allow","Principal":"*","Action":"s3:GetObject","Resource":"arn:aws:s3:::elliemaetestbucket1/*"}]}'}
I want to read "Sid" value and compare it with a string that I am getting from my yaml file. Dictionary can have multiple sids but I need to stop where my sid matches with the string that I am pulling from yaml. I am sure I am missing something very simple. But I have tried almost all the solutions most of the time I get unicode object not callable error.
Can somebody please provide some direction on how I can access it. I know this would be something very simple but I am sorry I am stuck at this from 2 days.
Your data's Policy key holds a literal JSON, you have to parse it first before you can access its nested fields:
import json
policy = json.loads(your_data["Policy"])
print(policy["Statement"][0]["Sid"]) # Sid of the first Statement
print(policy["Statement"][1]["Sid"]) # Sid of the second Statement

storing python list into mysql and accessing it

How can I store python 'list' values into MySQL and access it later from the same database like a normal list?
I tried storing the list as a varchar type and it did store it. However, while accessing the data from MySQL I couldn't access the same stored value as a list, but it instead it acts as a string. So, accessing the list with index was no longer possible. Is it perhaps easier to store some data in the form of sets datatype? I see the MySQL datatype 'set' but i'm unable to use it from python. When I try to store set from python into MySQL, it throws the following error: 'MySQLConverter' object has no attribute '_set_to_mysql'. Any help is appreciated
P.S. I have to store co-ordinate of an image within the list along with the image number. So, it is going to be in the form [1,157,421]
Use a serialization library like json:
import json
l1 = [1,157,421]
s = json.dumps(l1)
l2 = json.loads(s)
Are you using an ORM like SQLAlchemy?
Anyway, to answer your question directly, you can use json or pickle to convert your list to a string and store that. Then to get it back, you can parse it (as JSON or a pickle) and get the list back.
However, if your list is always a 3 point coordinate, I'd recommend making separate x, y, and z columns in your table. You could easily write functions to store a list in the correct columns and convert the columns to a list, if you need that.

Store repetitive data in python?

I'm working on a small task with excel sheet and python and the problem that I'm facing is i have few lines of code to perform string manipulation on the data which i fetch from the sheet. Since i got plenty of sheets,sometimes only limited number of sheets are required and couple of time whole excel sheet to perform string manipulation i can't write the same code everywhere so i thought of performing the operation once and storing it like oldvalue : newvalue so that whenever i read oldvalue i don't have to do manipulation again just fetch the newvalue from there. Now i tried using dictionary which is the best way to do it but the problem with using it is my key and value can both be repetitive and i don't want to update my previous entry with it. As per my knowledge we can't achieve it using dictionary. So what I'm asking is whether we have some kind of different data type to store it? Or do we actually need one? Can you help me figure out a way to solve it without using any data type?
EDIT :
The point is I'm getting the data from excel sheet and performing string manipulation on it and sometimes the key and the value are getting repetitive and since i'm using dictionary, it's updating previous value which i don't want to.
This will check if your dictionary contains a value for a specified key. If not, you can manipulate your string and save it for that key. If it does, it will grab that value and use it as your manipulated string.
""" Stuff is done. New string to manipulated is found """
if key not in dict:
value = ... #manipulated string
dict[key] = value
else:
manipulated_string = dict[key] #did this before, have the value already

How should python dictionaries be stored in pytables?

pytables doesn't natively support python dictionaries. The way I've approached it is to make a data structure of the form:
tables_dict = {
'key' : tables.StringCol(itemsize=40),
'value' : tables.Int32Col(),
}
(note that I ensure that the keys are <40 characters long) and then create a table using this structure:
file_handle.createTable('/', 'dictionary', tables_dict)
and then populate it with:
file_handle.dictionary.append(dictionary.items())
and retrieve data with:
dict(file_handle.dictionary.read())
This works ok, but reading the dictionary back in is extremely slow. I think the problem is that the read() function is causing the entire dictionary to be loaded into memory, which shouldn't really be necessary. Is there a better way to do this?
You can ask PyTables to search inside the table, and also create an index on the key column to speed that up.
To create an index:
table.cols.key.createIndex()
To query the values where key equals the variable search_key:
[row['value'] for row in table.where('key == search_key')]
http://pytables.github.com/usersguide/optimization.html#searchoptim

Categories