1
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.

Rahul K P
  • 15,740
  • 4
  • 35
  • 52

2 Answers2

2

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
Rahul K P
  • 15,740
  • 4
  • 35
  • 52
0

try this

list_object[0].encode("utf-8").decode()

or you can try this one also :

import json
json.loads(list_object[0])
  • No it din't work. o/p ---- resp = directreceipts[0].encode("utf-8").decode() AttributeError: 'dict' object has no attribute 'encode' – Chaitanya SH Oct 17 '22 at 18:36
  • resp = json.loads(directreceipts[0]) print(resp) TypeError: the JSON object must be str, bytes or bytearray, not dict – Chaitanya SH Oct 17 '22 at 18:38