TypeError: unsupported operand for +: 'dict' and 'str' in python
Question:
Im writing a code in AWS Lambda. I need to read a json file and depends on what data need to capture different values from that json file. Please find the below code
fileobj =s3.get_object(Bucket=srcbucname, Key=uploadfilename)
filedata =fileobj["Body"].read().decode('utf-8')
filejson = json.loads(filedata) # holds json file data
print(filejson)
dict1 = {"orders":["['items'][0]['ordernumber']","['items'][0]['name']"],"transaction":["['items'][0]['trans_id']"]}
fileperson = filejson['items'][0]['name'] #Depends on what json file contains, need to pull desired details
print(fileperson)
key = dict1[fileperson]
for i in key:
j = i
print(filejson+j) # Here im getting [ERROR] TypeError: unsupported operand type(s) for +: 'dict' and 'str'
print("Details provided")
Can you please provide me solution how to resolve [ERROR] TypeError: unsupported operand type(s) for +: ‘dict’ and ‘str’ and take output as per the scenario?
Answers:
You can’t use +
operator for dict
and str
. if you want to print both use comma separator.
print(filejson, j)
Or cast both to str
:
print(f"{filejson} {j}")
Im writing a code in AWS Lambda. I need to read a json file and depends on what data need to capture different values from that json file. Please find the below code
fileobj =s3.get_object(Bucket=srcbucname, Key=uploadfilename)
filedata =fileobj["Body"].read().decode('utf-8')
filejson = json.loads(filedata) # holds json file data
print(filejson)
dict1 = {"orders":["['items'][0]['ordernumber']","['items'][0]['name']"],"transaction":["['items'][0]['trans_id']"]}
fileperson = filejson['items'][0]['name'] #Depends on what json file contains, need to pull desired details
print(fileperson)
key = dict1[fileperson]
for i in key:
j = i
print(filejson+j) # Here im getting [ERROR] TypeError: unsupported operand type(s) for +: 'dict' and 'str'
print("Details provided")
Can you please provide me solution how to resolve [ERROR] TypeError: unsupported operand type(s) for +: ‘dict’ and ‘str’ and take output as per the scenario?
You can’t use +
operator for dict
and str
. if you want to print both use comma separator.
print(filejson, j)
Or cast both to str
:
print(f"{filejson} {j}")