Reputation: 21
print(type(directreceipts))
print(directreceipts)
o/p
1
2
<class 'list'>
['{\n "quantityOfUnits": 1500,\n "ownerOnDespatch": "100038",\n "packSize": 3\n}', '{\n "quantityOfUnits": 2500,\n "ownerOnDespatch": "100038",\n "packSize": 4\n}']
want to convert the list of strings to dictionary and access the values and also want to eleminate the \n.
Upvotes: 1
Views: 88
Reputation: 16081
You don't need to try to remove \n
here. Just parse the string with json
.
import json
directreceipts = [json.loads(d) for d in directreceipts]
Output:
[{'quantityOfUnits': 1500, 'ownerOnDespatch': '100038', 'packSize': 3},
{'quantityOfUnits': 2500, 'ownerOnDespatch': '100038', 'packSize': 4}]
You can access the values like,
Single-value access,
In [1]: directreceipts[0]['quantityOfUnits']
Out[1]: 1500
Ideally, iterate through and access the values
In [2]: for item in directreceipts:
...: print(item['quantityOfUnits'])
...:
1500
2500
To find the sum of those values, Using list comprehension.
In [3]: sum([item['quantityOfUnits'] for item in directreceipts])
Out[3]: 4000
Upvotes: 2
Reputation: 128
try this
list_object[0].encode("utf-8").decode()
or you can try this one also :
import json
json.loads(list_object[0])
Upvotes: 0