I have a List with multi lists of objects:
ob = Obj()
for p in l:
list_url_commune = scrapingCities(base_url, p)
for u in list_url_commune:
list_name = scaping_creches(base_url, u, number_page)
list_dep.append(list_name)
json_string = json.dumps([ob.__dict__ for ob in list_dep])
print json_string
list_dep is the list with all the lists with Objects
Then, I would like to convert all the Objects in only one JSON.
In my case, I have an error with json.dumps([ob.__dict__ for ob in list_dep])
(notice: it works fine if I have only one list but here it is a List of lists)
AttributeError: 'list' object has no attribute '__dict__'
Thanks for your help !
Pedro
Just like you noticed yourself, it works fine with a list of objects, but not with a list of lists of objects.
You need to go deeper:
json.dumps([[ob.__dict__ for ob in lst] for lst in list_dep])
Related
How can I simplify the following:
imgs = []
for i, obj in enumerate(objlist):
imgs.append( foo(obj, f"img-{i}.png") )
where objlist an array of objects
and foo is a method that processes the object and saves an image receiving both the object and the new file name, it returns the same name given.
This is a simple transformation into a list comprehension:
imgs = [foo(obj, f"img-{i}.png") for (i, obj) in enumerate(objlist)]
(btw you forgot the in in your for loop.
Also, see this answer on the general problem of converting nested for loops into a single list comprehension.
I have a list - list_of_objects = [<obj1>,<obj2>]. Each object has an attribute <ob1j>.content. Each content attribute holds a list of dictionaries [{"key":"value"}, {"key":"value"}]. How do I use list comprehension to "unpack" these dictionaries into a single list? Example that doesn't work:
list_of_dictionaries = [dict for obj in list_of_objects for item in obj.content]
Basically I want to turn the below loop that works into a comprehension:
for obj in list_of_objects:
new_list.extend(obj.content)
Calling dir on the object gives you back all the attributes of that object, including python special attributes.You can always filter out the special methods by using a list comprehension.
I have some data like:
['6005,280', '6005,2751', '6005,260']
and I want to convert them into a list like:
[['6005','280'],['6005','2751'],['6005','260']]
I use
for i in range(len(mainText)):
target_list.append(int(x) for x in mainText[i].split(','))
But got some crazy output like:
[<generator object main.<locals>.<genexpr> at 0x000000DA61784C78>, <generator object main.<locals>.<genexpr> at 0x000000DA61784B10>, <generator object main.<locals>.<genexpr> at 0x000000DA61784CF0>]
So what is the correct way to do that?
Code:
import csv
def main():
inputfile=open('price.csv','r')
mainText=mainPart(inputfile)
## print(mainText)
target_list=[]
for i in range(len(mainText)):
target_list.append(int(x) for x in mainText[i].split(','))
print(target_list)
def mainPart(file):
## import items with first row
rowsWithEnter1=[row for row in file]
## del first row
rowsWithEnter2=rowsWithEnter1[1:]
rows=[]
for i in range(len(rowsWithEnter2)):
rows.append(rowsWithEnter2[i].strip('\n'))
return rows
main()
When you have a comprehension (like int(x) for x in ...) inside parentheses, it is interpreted as a generator, which is a special type of object which can then be iterated over to produce a list. The crazy output you're seeing is because you've actually created a list of generators, instead of a list of lists. To interpret your comprehensions as lists instead of generators, you just need to put them in square brackets:
for i in range(len(mainText)):
target_list.append([int(x) for x in mainText[i].split(',')])
A simple way to achieve what I think you want is the following:
mainText = ['6005,280', '6005,2751', '6005,260']
target_list = [elem.split(',') for elem in mainText]
A list comprehension should work:
[x.split(',') for x in mainText]
A less preferable alternative to #francisco's answer:
list(map(str.split, mainText))
Here's one way using list comprehension
l = ['6005,280', '6005,2751', '6005,260']
[list(item.split(',')) for item in l]
I have a pickle file having many objects. I need to have one proper object by combining all the other objects in the file. How can I do that. I tried using many commands, but none seems to work.
objs = []
while True:
try:
f = open(picklename,"rb")
objs.append(pickle.load(f))
f.close()
except EOFError:
break
Like the one above as shown.
OBJECT stored image :
<nltk.classify.naivebayes.NaiveBayesClassifier object at 0x7fb172819198>
<nltk.classify.naivebayes.NaiveBayesClassifier object at 0x7fb1719ce4a8>
<nltk.classify.naivebayes.NaiveBayesClassifier object at 0x7fb1723caeb8>
<nltk.classify.naivebayes.NaiveBayesClassifier object at 0x7fb172113588>
You should use .extend() to append all items in the list to objs:
(Assuming pickle.load(f) returns a list of objects)
objs.extend(pickle.load(f))
I'm trying to write a function to convert a python list into a JSON array of {"mpn":"list_value"} objects, where "mpn" is the literal string value I need for every object but "list_value" is the value from the python list. I'll use the output of this function for an API get request.
part_nums = ['ECA-1EHG102','CL05B103KB5NNNC','CC0402KRX5R8BB104']
def json_list(list):
lst = []
d = {}
for pn in list:
d['mpn']=pn
lst.append(d)
return json.dumps(lst, separators=(',',':'))
print json_list(part_nums)
This current function is not working and returns last value in the python list for all JSON objects:
>[{"mpn":"CC0402KRX5R8BB104"},{"mpn":"CC0402KRX5R8BB104"},{"mpn":"CC0402KRX5R8BB104"}]
However, of course I need my function to return the unique list values in the objects as such:
>[{"mpn":"ECA-1EHG102"},{"mpn":"CL05B103KB5NNNC"},{"mpn":"CC0402KRX5R8BB104"}]
Bottom line is I don't understand why this function isn't working. I expected I could append a dictionary with a single {key:value} pair to a python list and it wouldn't matter that all of the dictionaries have the same key because they would be independent. Thanks for your help.
You are adding the exact same dictionary to the list. You should create a new dictionary for each item in the list:
json.dumps([dict(mpn=pn) for pn in lst])
As explained by others (in answers) you should create a new dictionary for each item on the list elsewhere you reference always the same dictionary
import json
part_nums = ['ECA-1EHG102','CL05B103KB5NNNC','CC0402KRX5R8BB104']
def json_list(list):
lst = []
for pn in list:
d = {}
d['mpn']=pn
lst.append(d)
return json.dumps(lst)
print json_list(part_nums)
print
[{"mpn": "ECA-1EHG102"}, {"mpn": "CL05B103KB5NNNC"}, {"mpn": "CC0402KRX5R8BB104"}]
import json
part_nums = ['ECA-1EHG102','CL05B103KB5NNNC','CC0402KRX5R8BB104']
def json_list(list):
lst = []
for pn in list:
d = {}
d['mpn']=pn
lst.append(d)
return json.dumps(lst)
print json_list(part_nums) # for pyhon2
print (json_list(part_nums)) # for python3