How to add a dictionary into list? - list

I have a dictionary in the form of a string and I need to add the string_dictionary to the list as a regular dictionary, because I need to enter the list and then the dictionary, like this:
Source[0]["name"]
But, the dictionary in the list is in "" and python not consider it like a dictionary.
dictionary = "{'name': 'liam', 'last name': 'something'}"
Source = [
dictionary,
]
print(Source)
Output:
["{'name': 'liam', 'last name': 'something'}"]

To parse the string to a dictionary, you can use ast.literal_eval:
from ast import literal_eval
dictionary = "{'name': 'liam', 'last name': 'something'}"
Source = [
literal_eval(dictionary),
]
print(Source[0]["name"])
Prints:
liam

Related

Access Python Dictionary elements containing dot in name

I have to read elements of of the following python dictionary:
dict = {'crawler.cmd': 'OS Path for CMD',
's3.failureBucket': 'Failure Bucket Name',
's3.landingBucket': 'Landing Bucket Name',
's3.rawBucket': 'Raw Bucket Name',
'src.name': 'StreamNameUpd'}
As the element name contains dots so, how would I access element with dot in name?
Given your dictionary:
my_dictionary = {'crawler.cmd': 'OS Path for CMD',
's3.failureBucket': 'Failure Bucket Name',
's3.landingBucket': 'Landing Bucket Name',
's3.rawBucket': 'Raw Bucket Name',
'src.name': 'StreamNameUpd'}
You can access any element just by putting its correspondant key in the square brackets like the following:
my_dictionary['crawler.cmd']
Output:
'OS Path for CMD'
Another way to get this:
my_dictionary.get('crawler.cmd')
With get() function you can also define a default value in case the key not in dict:
my_dictionary.get('crawler.cmd', "my_value")
Output:
'OS Path for CMD'

Fetch Json Field value using Values in Django

I have a JSON field in my model and by using values option, I would like to get the key value present in the JSON field.
Assume my JSON field value is:
{"key1":"value1","key2":"value2"}
MyClass.objects.values("field1","field2","JSON Key")
Let JSON Key be "Key1"
Expected O/P:
[{field1:Value1,field2:value2,Key1:value1}]
A better solution (for Django >= 1.11) would be to use KeyTextTransform, like so:
from django.contrib.postgres.fields.jsonb import KeyTextTransform
MyModel.objects\
.annotate(key1=KeyTextTransform('key1', 'myjsonfield'))\
.values('field1','field2','key1')
I have written a custom manager function in ActiveQuerySet which accepts a list of fields and give get the particular field information from the object.
I have written the script for simple json structure..but where as u can change the way of processing json according to requirement.
The ActiveQuerySet class is as below.
class ActiveQuerySet(models.QuerySet):
def custom_values(self,*args,**kwargs):
model_fields = self.model._meta.get_fields()
model = [str(i.name) for i in model_fields]
json_fields = [str(i.name) for i in model_fields if i.get_internal_type() == 'JSONField']
responses = []
for one in self:
one_value = {}
for i in args[0]:
if i in model: # search if field is in normal model
one_value[i]=str(getattr(one,i))
else:
for jf in json_fields: #get all json fields in model
try:
json_value = eval(getattr(one,jf)) #eval to json or dict format if required
except:
json_value = getattr(one,jf)
json_keys = json_value.keys() #get the keys from json data stored
if i in json_keys:#check if key is present
one_value[i] = json_value[i]
responses.append(one_value)
return responses
MyModel.objects.all().custom_values(['field1','field2','key(which is present in JOSN field)'])
Assume my json data is stored as
{"cluster": "Mulchond", "2962": "2016-12-13", "2963": "1", "2964": "4", "2965": "0", "2966": "0", "2967": "0", "2968": "0.0318", "2969": "0.0705", "2970": "", "2971": "", "2972": "", "2973": "17.256", "2974": "48.8351", "2975": "142", "2976": "783", "2977": "276", "2978": "0.05237", "2979": "70", "2980": "0.05237", "2981": "", "2982": "", "2983": "", "2984": "142", "2985": "32", "2986": "", "2987": "20.773551", "2988": "73.649422"}
from this I want to get value of key '2988', My Query be like
MyModel.objects.filter().custom_values(['id','2988'])
o/p :
[{'2987': '20.730995', 'id': '66302'},
{'2987': '20.766556', 'id': '66303'},
{'2987': '20.773551', 'id': '66304'}]
where 'id is generated by Django and '2987' is one key which is present in JSON Field

Django ORM call to obtain multiple fk values?

models.py (derived from existing db)
class IceCreamComponent(models.Model):
name = models.CharField
#can be 'flavor', 'nut', etc
class IceCream(models.Model):
name = models.CharField
component = models.ForeignKey(IceCreamComponent)
value = models.CharField #will correspond to the component
The context behind this database is that 'IceCream' reports will come in from someone who's only purpose is to report back on a certain component (i.e. my 'extras' reporter will report the name of the ice cream and the extra it contained). It is assumed that all needed reports are in the db when queried so that something like:
IceCreams = IceCream.objects.values('name', 'component__name', 'value')
will return something akin to:
[
{'name': 'Rocky road', 'component__name': 'ice cream flavor', 'value':'chocolate'},
{'name': 'Rocky road', 'component__name': 'nut', 'value':'almond'},
{'name': 'Rocky road', 'component__name': 'extra', 'value':'marshmallow'},
{'name': 'Vanilla Bean', 'component__name': 'ice cream flavor', 'value':'vanilla'},
{'name': 'Vanilla Bean', 'component__name': 'extra', 'value':'ground vanilla bean'},
]
However, as you can imagine something like:
[
{'name': 'Rocky Road', 'ice cream flavor': 'chocolate', 'nut': 'almond', 'extra':'marshmallow' },
{'name': 'Vanilla Bean', 'ice cream flavor': 'vanilla', 'extra':'ground vanilla bean'}
]
is much more usable (especially considering I'd like to use this in a ListView).
Is there a better way to query the data or will I need to loop through the ValuesQuerySet to achieve the desired output?
Can't you reconstruct the list from the original result?
results = []
for row in vqueryset:
converted_row = {}
converted_row[row['component__name']] = row['value']
converted_row['name'] = row['name']
results.append(converted_row)
Of course you would want to paginate the original result before evaluating it (turning it into a list).
oh, you asked if there's a better way. I'm doing it this way because I couldn't find a better way anyway.
Here is the solution I came up with.
processing = None
output = []
base_dict = {}
for item in IceCreams:
# Detect change current site code from ordered list
if item['name'] != processing:
processing = item['name']
# If base_dict is not empty add it to our output (only first one)
# TODO see if there's a better way to do first one
if base_dict:
output.append(base_dict)
base_dict = {}
base_dict['name'] = item['name']
base_dict[item['component__name']] = item['value']

Using the Facebook Graph API to search for an exact string

I want to use the Facebook Graph API to search for exact page matches to "My String".
I tried https://graph.facebook.com/search?q=%22My%20String%22&type=page - but it returns pages that match either "String" or "My".
How do I construct a search query that returns only exact matches to the quoted string?
Currently, you can't. It's triaged on the wishlist.
So, you'll have to wrap the request, in Python :
import requests
query = 'My String'
r = requests.get('https://graph.facebook.com/search?q=%s&type=page' % query)
result = r.json
result['data'] = [ item for item in result['data']
if query.lower() in item['name'].lower() ]
print [ item['name'] for item in result['data'] ]
Now you only have exact matches.
try using Unicode, U+0200 is the space bar, so concatenate "My", U+0200, and "String". No clue if that works.

making separate array from existing json django

I have this array of JSON:
[{'pk': 4L, 'model': u'logic.member', 'fields': {'profile': 3L, 'name': u'1', 'title': u'Mr', 'dob': datetime.date(1983, 1, 1), 'lastname': u'jkjk', 'redressno': u'jdsfsfkj', 'gender': u'm'}}, {'pk': 5L, 'model': u'logic.member', 'fields': {'profile': 3L, 'name': u'2', 'title': u'Mr', 'dob': datetime.date(1983, 1, 1), 'lastname': u'jkjk', 'redressno': u'jdsfsfkj', 'gender': u'm'}}]
I want to make separate array of JSON for only fields property.
What I tried is:
memarr=[]
for index,a in data1:
print index
print a
memarr[index]=a[index].fields
And it is giving an error of:
too many values to unpack
Please correct.
First of all, data1 is a list, so you can't unpack it into 2 variables.
If you want the index, you have to use something like enumerate.
Second, you can't assign to a list via indexing if the key doesn't exist. You have to append or use another valid list insert method.
Third, a[index].fields doesn't really make sense - there is no key in a that would be associated with an integer index and fields is not an attribute.
You're probably looking for something like this:
memarr = []
for index, a in enumerate(data1):
memarr.append(a['fields'])
So many things wrong with that snippet...
Anyway:
memarr = [a['fields'] for a in data]