Append object to sub json key PYTHON - python

I am trying to append an object in a loop to one of two sub keys created in a json object.
for agency in q:
dashboard[agency.id]= []
dashboard[agency.id].append({"name": agency.agency.name})
dashboard[agency.id].append({"stats": []})
dashboard[agency.id].append({"users": []})
for row in stats:
if row['is_agency']:
dashboard[row['agency_id']['stats']].append(dict(row))
else:
dashboard[row['agency_id']['users']].append(dict(row))
But it is throwing an error of:
dashboard[row['agency_id']]['users'].append(dict(row))
TypeError: list indices must be integers, not str
If I remove ['users'] or ['stats'] key it appends to the agency.id key just fine. But when I try to add it as a second level key, it throws the above error.
As the json object will always have the 3 sub keys (name[0], stats[1], users[2]) I have also then tried using:
for row in stats:
if row['is_agency']:
dashboard[row['agency_id']][1].append(dict(row))
else:
dashboard[row['agency_id']][2].append(dict(row))
That results in an error of the following:
dashboard[row['agency_id']][2].append(dict(row))
AttributeError: 'dict' object has no attribute 'append'

You are confusing the types and methods of your objects, as user #Moses Koledoye shows, if you do:
dashboard[row['agency_id']][1]['stats'].append(row)
Step by Step:
row['agency_id'] is an Int, so
dashboard[row['agency_id']] #has type list
will give you the value of the key row['agency_id'], of type List
dashboard[row['agency_id']][1]
gives to you the value in the position 1 of the list
`dashboard[row['agency_id']][1]['stats']` #is a List also
finally gives to you the list of stats (taking it as example), that's why you can use the append method:
dashboard[row['agency_id']][1]['stats'].append(row)

Related

i am getting an error "TypeError: 'type' object does not support item assignment"

I am a beginner in python. I am trying to pass a query file i.e file2 which contains the list of some protein accession numbers to check the presence of those accessions in the parent tab-delimited dictionary file i.e Book2.txt, I am getting an error "TypeError: 'type' object does not support item assignment"
my code goes as follows:
for i in open ("Book2.txt"):
split_i=i.split('\t')
dict['Master Protein Accessions']=i.rstrip //TypeError: 'type' object does not support item assignment
for j in open("file2.txt"):
if j.rstrip in dict:
print(dict(j.rstrip))
dicts = {}
for i in open('Book2.txt'):
split_i = i.split('\t')
dicts[split_i[0]] = i.rstrip()
for j in open('file2.txt'):
if j.rstrip() in dicts:
print(dicts[j.rstrip()]
first of all "dict" is a keyword you cant use as dictionary name and then you have to create an empty dictionary or default dictionary to assign some value.
so you can do:
d = {} or d = dict()
for i in open ("Book2.txt"):
split_i=i.split('\t')
d['Master Protein Accessions']=i.rstrip()
for j in open("file2.txt"):
if j.rstrip() in d:
print(d[j.rstrip()])

Casting a value in a dictionary from str to float

I have been trying to look at other questions and not found anything that works for me. I have a list if dictionaries (trips) and want to access the values in each dictionary within the list of trips, and convert if from a string to a float.
If i take trips[0] output is:
# {'pickup_latitude': '40.64499',
# 'pickup_longitude': '-73.78115',
# 'trip_distance': '18.38'}
I am trying to build a function that iterates through the list of dictionaries, accessing the values and transferring them to floats.
I have tried various versions of the code below, including trying to build a new dictionary and returning that
def float_values(trips):
for trip in trips:
for key, value in trip.items():
value = float(value)
return
float_values[0] should output:
# {'pickup_latitude': 40.64499,
# 'pickup_longitude': -73.78115,
# 'trip_distance': 18.38}
Continuously getting
'function' object is not subscriptable'
OR
'NoneType' object is not subscriptable
If you what to override your values from the dictionary you should do something like this
def float_values(trips):
for trip in trips:
for key, value in trip.items():
trip[key] = float(value)
return trips
By doing value = float(value) you are writing temporary the float value and not saving it anywhere
Simply what you need to do is change value inside the dictionary:
for list_dict in list_of_dicts:
for key, value in list_dict.items():
list_dict[key] = float(value)

pandas isin append unhashable type: 'list' error

I ran out of idea on how to add new items to filter list in pandas.
Example:
OldProducts = ProductInfo[ProductInfo['MerchantID'].isin(['A store', 'B store'])]
OldProductsId = list(OldProducts.PID.unique())
OldProductsId2 = ['VayjE7nrDl', 'BYbcAAuV0r', 'hu2y8rYIbN', 'YXELEovcwK']
OldProductsId.append(OldProductsId2)
DetailProductInfo = DetailProductInfo [~DetailProductInfo ['PID'].isin(OldProductsId)]
The error is like this:
TypeError: unhashable type: 'list'
The append method will add the item you pass as another item in the list. If that item happens to be another list then the final element in your list will be the OldProductsId2 list. Use extend instead.
Change OldProductsId.append(OldProductsId2) to OldProductsId.extend(OldProductsId2)
You've appended OIdProductsId2 to OldProductsId, so now OldProductsId is a list of (presumably) strings plus a list object. So to correct your code change this line:
OldProductsId.append(OldProductsId2)
To:
OldProductsId.extend(OldProductsId2)
And the error should disappear.

Python : AttributeError: 'int' object has no attribute 'append'

I have a dict of int, list. What I'm trying to do is loop through `something' and if the key is present in the dict add the item to the lsit or else create a new list and add the item.
This is my code.
levels = {}
if curr_node.dist in levels:
l = levels[curr_node.dist]
l.append(curr_node.tree_node.val)...........***
else:
levels[curr_node.dist] = []
levels[curr_node.dist].append(curr_node.tree_node.val)
levels[curr_node.dist] = curr_node.tree_node.val
My question is two-fold.
1. I get the following error,
Line 27: AttributeError: 'int' object has no attribute 'append'
Line 27 is the line marked with ***
What am I missing that's leading to the error.
How can I run this algorithm of checking key and adding to a list in a dict more pythonically.
You set a list first, then replace that list with the value:
else:
levels[curr_node.dist] = []
levels[curr_node.dist].append(curr_node.tree_node.val)
levels[curr_node.dist] = curr_node.tree_node.val
Drop that last line, it breaks your code.
Instead of using if...else, you could use the dict.setdefault() method to assign an empty list when the key is missing, and at the same time return the value for the key:
levels.setdefault(curr_node.dist, []).append(curr_node.tree_node.val)
This one line replaces your 6 if: ... else ... lines.
You could also use a collections.defaultdict() object:
from collections import defaultdict
levels = defaultdict(list)
and
levels[curr_node.dist].append(curr_node.tree_node.val)
For missing keys a list object is automatically added. This has a downside: later code with a bug in it that accidentally uses a non-existing key will get you an empty list, making matters confusing when debugging that error.

Create a list of defaultdict in python

I am doing the following :
recordList=[lambda:defaultdict(str)]
record=defaultdict(str)
record['value']='value1'
record['value2']='value2'
recordList.append(record)
for record in recordList:
params = (record['value'],record['value2'],'31')
i am getting the error :
TypeError: 'function' object is not
subscriptable
what is wrong here ?
recordList=[lambda:defaultdict(str)]
creates a list with a function that returns defaultdict(str). So it's basically equivalent to:
def xy ():
return defaultdict(str)
recordList = []
recordList.append( xy )
As such, when you start your for loop, you get the first element from the list, which is not a list (as all the other elements you push to it), but a function. And a function does not have a index access methods (the ['value'] things).
recordList is a list with 1 element which is a function.
If you replace the first line with
recordList = []
the rest will wor.
you're adding a lambda to recordList, which is of type 'function'. in the for .. loop, you're trying to subscript it (record['value'], record['value2'], etc)
Initialize recordList to an empty list ([]) and it will work.

Categories